0

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'},
];
  • Summary answer: put items into an object with `id` as the key, then iterate through `sortArray` and look each one up. – Thomas Aug 01 '18 at 13:30
  • Is same as https://stackoverflow.com/questions/13304543/javascript-sort-array-based-on-another-array You find the right answer there! – Erelke Aug 01 '18 at 13:31

5 Answers5

3

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);
31piy
  • 23,323
  • 6
  • 47
  • 67
1

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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);
Faly
  • 13,291
  • 2
  • 19
  • 37
0

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

var ordered = sortArray.map(id => {
    return items.filter(item => {
        return id == item.id
    });
});
Dani
  • 116
  • 1
  • 2
  • 8