1

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.

4
  • 4
    [2: {name: Joel,... is invalid syntax. Arrays do not have key-value pairs. Also, strings need delimiters. Commented Jan 16, 2019 at 5:14
  • @tha07 you're previous desired output and current output is different. which one you want to have ? Commented Jan 16, 2019 at 5:30
  • I want the failed output to be ordered by the name attribute. Commented Jan 16, 2019 at 5:32
  • I think I misunderstood the situation. Code Maniac's answer is correct. My edit to the array was wrong Commented Jan 16, 2019 at 5:42

1 Answer 1

3

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)

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

3 Comments

I corrected my array. is this code still okay to the question.
@tha07 yeah. i added this answer by removing your syntax errors only. otherwise it won't even run
sorry for the situation. I misunderstood it. Thank you for your help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.