Home > Mobile >  Sorting Array of objects by a specific key
Sorting Array of objects by a specific key

Time:10-24

I have the follow array of JavaScript objects

Data = [
{name: “Ben”,region: “Southeast Asia”, type: “Building”, value: 5},
{name: “Junior”,region: “North America”, type: “person”, value: 3},
{name: “Nort”,region: “Central Asia”, type: “Building”, value: 3}, 
{name: “Julion”,region: “Great Basin”, type: “person”, value: 2},
{name: “Travis”,region: “Eastern Europe”, type: “person”, value: 9}
];

How would I sort or filter this array with objects such that I get the following array:

Data = [
{name: “Julion”,region: “Great Basin”, type: “person”, value: 2},
{name: “Junior”,region: “North America”, type: “person”, value: 3},
{name: “Nort”,region: “Central Asia”, type: “Building”, value: 3},
{name: “Ben”,region: “Southeast Asia”, type: “Building”, value: 5}
];

I am not sure if I can use sort(a,b)or filter(row => )

CodePudding user response:

arr.sort((a,b)=>a.value-b.value)

is this what you are looking for?

CodePudding user response:

I think sort() will be suitable in this case.

The sort() method accepts a comparator function. This function accepts two arguments (both presumably of the same type) and its job is to determine which of the two comes first.

For Ascending :
Data.sort((a,b)=> (Data.name > Data.name ? 1 : -1))

For Descending :
Data.sort((a,b)=> (Data.name > Data.name ? -1 : 1))

CodePudding user response:

just do this

const Data = [
{name: “Ben”,region: “Southeast Asia”, type: “Building”, value: 5},
{name: “Junior”,region: “North America”, type: “person”, value: 3},
{name: “Nort”,region: “Central Asia”, type: “Building”, value: 3}, 
{name: “Julion”,region: “Great Basin”, type: “person”, value: 2},
{name: “Travis”,region: “Eastern Europe”, type: “person”, value: 9}
];
Data.sort((a, b) => a.value - b.value)
console.log(Data)
//!Expected Output
Data = [
  { name: 'Julion', region: 'Great Basin', type: 'person', value: 2 },
  { name: 'Junior', region: 'North America', type: 'person', value: 3 },
  { name: 'Nort', region: 'Central Asia', type: 'Building', value: 3 },
  { name: 'Ben', region: 'Southeast Asia', type: 'Building', value: 5 },
  { name: 'Travis', region: 'Eastern Europe', type: 'person', value: 9}
]

and done, its called as ASC, but if u were need to sort it from the higher value just swap the

Data.sort((a, b) => a.value - b.value)
//! Into
Data.sort((a, b) => b.value - a.value)
  • Related