Move array objects within itself according to a certain object's property

24 views Asked by At

Suppose we have an array of objects and we want it to move some objects with a certain property to the beginning of the array, For more clarity I will give an example:

let arr = [
  {id:5 , tag: "X" , name:"mohsen"},
  {id:1 , tag: "A" , name:"hasan"},
  {id:3 , tag: "P" , name:"ali"},
  {id:8 , tag: "D" , name:"mehran"},
  {id:4 , tag: "C" , name:"nima"},
  {id:12 , tag: "A" , name:"keivan"},
  {id:6 , tag: "P" , name:"pedram"},
  {id:17 , tag: "X" , name:"masoud"},
  {id:20 , tag: "D" , name:"hadi"},
];

at this moment if we want to move objects with tag:"P" to beginning of array like below:

[
  {id: 3 ,name: "ali",tag: "P"}, 
  {id: 6,name: "pedram",tag: "P"},
  {id: 5,name: "mohsen",tag: "X"},
  {id: 1,name: "hasan",tag: "A"},
  {id: 8,name: "mehran",tag: "D"}, 
  {id: 4,name: "nima",tag: "C"}, 
  {id: 12,name: "keivan",tag: "A"},
  {id: 17,name: "masoud",tag: "X"},
  {id: 20,name: "hadi",tag: "D"}
]

What should we do?

1

There are 1 answers

10
masoud On

for more description, at the first we map on array then for every item of array we check that item[propName] === propValue condition if it is true then we cut this item from its place with const b = arr.splice(index , 1); and put it at beginning of array with arr.splice(place,0,...b); , the place variable track new index of beginning of array.

let arr = [
  {id:5 , tag: "X" , name:"mohsen"},
  {id:1 , tag: "A" , name:"hasan"},
  {id:3 , tag: "P" , name:"ali"},
  {id:8 , tag: "D" , name:"mehran"},
  {id:4 , tag: "C" , name:"nima"},
  {id:12 , tag: "A" , name:"keivan"},
  {id:6 , tag: "P" , name:"pedram"},
  {id:17 , tag: "X" , name:"masoud"},
  {id:20 , tag: "D" , name:"hadi"},
];



function reorderListByProp(propName , propValue) {
  const rem = [];
  let place = 0;
  arr.map((item , index) => {
    if(item[propName] === propValue) {
      const b = arr.splice(index , 1);
      arr.splice(place,0,...b);
      place++;
    }
  });

  return arr;
}

console.log(reorderListByProp('tag' , 'P'));