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

231
Views
How to move the objects to the top inside array based on the matched key

I have an array of objects with different keys I want to move the objects to the top based on the key I want.

Given array based on the status: "Active" I want all the matched objects to be moved top

[
   {name: "abc", age: "20", status: "Active"}, 
   {name: "xyz", age: "21", status: "Inactive"}, 
   {name: "pqr", age: "22", status: "Active"}
]

Expected Output:

[
   {name: "abc", age: "20", status: "Active"}, 
   {name: "pqr", age: "22", status: "Active"}, 
   {name: "xyz", age: "21", status: "Inactive"}
]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

let list = [{
  name: "abc",
  age: "20",
  status: "Active"
}, {
  name: "xyz",
  age: "21",
  status: "Inactive"
}, {
  name: "pqr",
  age: "22",
  status: "Active"
}]
list.sort((a, b) => (a.status !== "Active") ? 1 : -1)
console.log(list)

Produces the following output

[
  { name: 'pqr', age: '22', status: 'Active' },
  { name: 'abc', age: '20', status: 'Active' },
  { name: 'xyz', age: '21', status: 'Inactive' }
]
about 4 years ago · Juan Pablo Isaza Report

0

Arrays have method Array.sort where you can pass function that return 1, -1 or 0 which corresponds to how to move element of an array

const arr = [{
  name: "abc",
  age: "20",
  status: "Active"
}, {
  name: "xyz",
  age: "21",
  status: "Inactive"
}, {
  name: "pqr",
  age: "22",
  status: "Active"
}]
console.log(arr.sort((a, b) => (a.status === b.status) ? 0 : a.status === "Active" ? -1 : 1))

about 4 years ago · Juan Pablo Isaza Report

0

you can change your code like this.

function handleData(arr, status) {
   if(!arr || arr.length == 0) return
   for(let i=0; i<arr.length; i++) {
    let item = arr[i];
    if(item.status == status) {
      arr.splice(i, 1);
      arr.unshift(item)
    }
   }
}
let arr = [{name: "abc", age: "20", status: "Active"}, {name: "xyz", age: "21", status: "Inactive"}, {name: "pqr", age: "22", status: "Active"}]

handleData(arr, 'Active')

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!