Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort array object based on another object

Tags:

javascript

it possible to sort and rearrange an array that looks like this:

items:[{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     },{
     id: '1',
     name: 'fdf'
     }]

to match the arrangement of this object:

 Item_sequence: {
        "5": {index: 1},
        "1": { index: 0 }
      }

Here is the output I’m looking for:

 items:[{
     id: '1',
     name: 'fdf'
     },{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     }]
like image 762
nurwadula Avatar asked Mar 21 '26 10:03

nurwadula


1 Answers

You could check if the index is supplied and if not take a lage value for sorting by delta of two items.

var data = { items: [{ id: '5', name: 'wa' }, { id: '3', name: 'ads' }, { id: '1', name: 'fdf' }] },
    sequence = { 5: { index: 1 }, 1: { index: 0 } };      

data.items.sort(({ id: a }, { id: b }) => 
    (a in sequence ? sequence[a].index : Number.MAX_VALUE) -
    (b in sequence ? sequence[b].index : Number.MAX_VALUE)
);

console.log(data.items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 112
Nina Scholz Avatar answered Mar 24 '26 01:03

Nina Scholz