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