简体   繁体   English

用另一个数组对对象数组进行排序

[英]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. 因此,在这种情况下,items数组应将ID = 1195的对象排在列表的第一位。 Also if there is only one id in the sortArray it should only display that object in the items array. 同样,如果sortArray中只有一个id,则它应仅在items数组中显示该对象。

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. 您可以遍历sort数组,并在每次迭代中找到源数组中的元素。 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). 看起来,您需要过滤对象数组,然后按sortArray的顺序对对象进行排序(顺便说一句,如果数据具有相同的类型,会更容易)。

 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 您可以使用array.sort和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 }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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