3

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.