sort array based on another array
itemsArray.sort(function(a, b){
return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});arr.sort((a, b) =>{
return sortingArray.indexOf(a) - sortingArray.indexOf(b);
});/**
* 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));
Also in JavaScript:
- include jquerty
- js numbers
- javascript check if a value is an int
- react ctx
- how to generate random string in javascript
- componentWillUnmount functional component for asynchronous requests
- moment for react
- javacript is checkbox checked
- javascript array merge
- replacing a value in string using aregular expression pyhton
- deploy create react app pm2
- knex.js insert two rows
- appinsights trackException javascript
- program to parenthesize an expression
- string charAt array js
- Javascript track mouse pointer
- access selected option in jquery
- route react
- upload bloob javascript
- comment dire le nombre de ligne html en cliquamt sur un boutton javascript
- vuejs import component
- how to change css with js
- jest mock mockname
- how to reload page on button click in javascript