简体   繁体   中英

Sort array of objects by another array

I have an array of objects that looks like this.

var items = [
  {id: 1150, title: 'im tyler'},
  {id: 1195, title: 'im josh'}
];

And another array that looks like this:

var sortArray = [
'1195',
'1150'
];

What i am trying to accomplish is a sorting based on result from the sort array. So in this scenario that items array should sort the object with id = 1195 as first in the list. Also if there is only one id in the sortArray it should only display that object in the items array.

Wanted result:

var Newitems = [
  {id: 1195, title: 'im josh'}
  {id: 1150, title: 'im tyler'},
];

You can loop over the sort array, and in each iteration find the element in the source array. If found, push the result to a new array.

Though it generates a new array, please note that the items still refer to the original array. The new array just contains the references to original items.

 var sortArray = [ '1195', '1150' ]; var items = [ {id: 1150, title: 'im tyler'}, {id: 1195, title: 'im josh'} ]; var res = []; sortArray.forEach(item => { res.push(items.find(i => i.id.toString() === item)); }); console.log(res); 

You could create an object from sort array and then use that object to sort.

 var items = [{id: 1150, title: 'im tyler'},{id: 1195, title: 'im josh'}]; var sortArray = ['1195','1150'].reduce((r, e, i) => Object.assign(r, {[e]: i}), {}) items.sort((a, b) => sortArray[a.id] - sortArray[b.id]); console.log(items) 

It looks like, you need to filter the array of objects and then sort the objects by the order of sortArray (btw, it would be easier if the data has the same type).

 var items = [{ id: 1150, title: 'im tyler' }, { id: 1195, title: 'im josh' }], sortArray = ['1195', '1150'].map(Number), result = items .filter(({ id }) => sortArray.includes(id)) .sort((a, b) => sortArray.indexOf(a.id) - sortArray.indexOf(b.id)); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can use array.sort and array.indexOf

 var items = [ {id: '1150', title: 'im tyler'}, {id: '1195', title: 'im josh'} ]; var sortArray = [ '1195', '1150' ]; items.sort((a, b) => sortArray.indexOf(a.id) - sortArray.indexOf(b.id)); console.log(items); 

You can do that using map and filter, like this:

 var ordered = sortArray.map(id => { return items.filter(item => { return id == item.id }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM