Home > database >  How to move the objects to the top inside array based on the matched key
How to move the objects to the top inside array based on the matched key

Time:01-13

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related