Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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'));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!