简体   繁体   中英

how to sort array object based on another object

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'
     }]

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; }

JavaScript specifically, First you have to apply loop to your array "items":

`
 let newArr = [];
 items.map(obj=>{

//obj will be the element of items array, here it is an object.

 if(Item_sequence.obj[id] !== undefined) {
   /*this condition will be satisfied when id from items array will be present as a 
   key in Item_sequence array*/

   insertAt(newArr, Item_sequence.obj[id] , obj) 
  }
 else{
   newArr.push(obj);
 }
})
//After checking on whole array here you assign a newArr value to items array.
items=newArr;

Hope that it will help you.

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