Answers for "sort array of objects based on another array javascript"

1

sort array based on another array

arr.sort((a, b) =>{  
	return sortingArray.indexOf(a) - sortingArray.indexOf(b);
});
Posted by: Guest on November-28-2020
0

sort objects by another array JS

const machines = [
  { id: 1, client: 'Machine A', state: 'Ready' },
  { id: 2, client: 'Machine B', state: 'Stopped' },
  { id: 3, client: 'Machine C', state: 'Active' },
  { id: 4, client: 'Machine D', state: 'Stopped' },
  { id: 5, client: 'Machine E', state: 'Active' },
  { id: 6, client: 'Machine F', state: 'Stopped' }
]

const sortedBy = {
  'Active'  : 0, 
  'Ready'   : 1, 
  'Stopped' : 2,
}

const result = machines.sort(
  (a, b) => sortedBy[a.state] - sortedBy[b.state]
)
Posted by: Guest on August-24-2021
0

sort array based on another array js

/**
 * Sort array of objects based on another array
 */

function mapOrder (array, order, key) {
  
  array.sort( function (a, b) {
    var A = a[key], B = b[key];
    
    if (order.indexOf(A) > order.indexOf(B)) {
      return 1;
    } else {
      return -1;
    }
    
  });
  
  return array;
};


/**
 * Example:
 */

var item_array, item_order, ordered_array;

item_array = [ 
  { id: 2, label: 'Two' }
, { id: 3, label: 'Three' }
, { id: 5, label: 'Five' }
, { id: 4, label: 'Four' }
, { id: 1, label: 'One'}
];

item_order = [1,2,3,4,5];

ordered_array = mapOrder(item_array, item_order, 'id');

console.log('Ordered:', JSON.stringify(ordered_array));
Posted by: Guest on September-24-2020
0

sort array of objects based on another array javascript

itemsArray.sort(function(a, b){  
  return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});
Posted by: Guest on October-07-2021

Code answers related to "sort array of objects based on another array javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language