Tharindu
Tharindu

Reputation: 339

Javascript Object Array Sorting Issue

I have a JavaScript array of objects to sort and arrange it as a new object array preserving the order.

My array of objects. I get them ordered in the way that I want. The index of the objects are 0,1 & 2 in this.

[{0: {name: 'Joel', age:25, id: 2}}, {1: {name: 'Sam', age: 23, id: 4}}, {2: {name: 'Tim', age:27, id: 3}}]

What I want is to make 'id' the index value. And I want it in ascending order of the 'name' (Preserving the above order)

[{2: {name: 'Joel', age:25, id: 2}}, {4: {name: 'Sam', age: 23, id: 4}}, {3: {name: 'Tim', age:27, id: 3}}]

I tried using this function.

for (i in members) {
    member[members[i].id] = members[i];
}

But it failed. The output was

[{}, {}, {name: "Joel", age:25, id: 2}, {name: "Tim", age:27, id: 3}, {name: "Sam", age: 23, id: 4}]

I tried using forEach and sort methods too. But all failed.

Is there any way to accomplish this in JavaScript.

Upvotes: 1

Views: 80

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

You can do it with help of map and sort.

let obj = [{0: {name: 'Joel', age:25, id: 2}}, {1: {name: 'Sam', age: 23, id: 4}}, {2: {name: 'Tim', age:27, id: 3}}]


let op = obj.map((e,index)=>{
  return{
    [e[index].id] : e[index]
  }
}).sort((a,b)=> Object.keys(a) - Object.keys(b))

console.log(op)

Upvotes: 3

Related Questions