-1
var object = [
    { name: 'Mar', age: 32 ,height:40},
    { name: 'Carla', age: 10 ,height:15},
    { name: 'Hazel', age: 5 ,height:80}
];

Is it possible to sort based on the age element and generate a new sorted object?

Expected result:

var newobject = [
    { name: 'Hazel', age: 5 ,height:80},
    { name: 'Carla', age: 10 ,height:15},
    { name: 'Mar', age: 32 ,height:40}
];

Or you could also return the result sorted in an array, instead of returning it in an object... whatever... uncomplicated, but return it sorted .

var new_sorted_array = [
   [Hazel, 5 ,80] , 
   [Carla, 10 ,15], 
   [Mar, 32 ,40]
];
1
  • 2
    object.sort(({age: a}, {age: b}) => a - b) Commented Jan 30, 2023 at 4:52

1 Answer 1

0

To achieve expected result, you can try below two options

  1. Using array sort method - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
  2. Second option is by looping array and using Object.values to get output in the format specified in question

var object = [
    { name: 'Mar', age: 32 ,height:40},
    { name: 'Carla', age: 10 ,height:15},
    { name: 'Hazel', age: 5 ,height:80}
];

//Sort array by property age
console.log("Sort by age", object.sort((a, b) => a.age -  b.age))

//Using object values
console.log("Sort by age -option2", object.map(v => Object.values(v)).sort((a, b) => a[1] - b[1]))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.