Array value replacement with corresponding id

Viewed 71

I have an array of objects of people, which contains:

  • id (of the person)
  • name (of the person)
  • likes (id of the person they like)

.

array = [{ id:1, name:"Adam", likes:2 },{ id:2, name:"Ben", likes:3 },{ id:3, name:"Cindy", likes:1 }];

The final array should have the id of the person they like replaced with their name

array = [{ id:1, name:"Adam", likes:"Ben" },{ id:2, name:"Ben", likes:"Cindy" },{ id:3, name:"Cindy", likes:"Adam" }];

Current Solution:

for(let i=0;i<array.length;i++){
    for(let j=0;array.length;j++){
        if(array[i].likes == array[j].id){
            array[i].likes = array[j].name;
        };
    };
};

Is there a more efficient way of doing this other than using 2 loops?

3 Answers

Here is the O(n) way:

 const byID = new Map(array.map(u => [u.id, u]));

 for(const u of array)
   u.likes = byID.get(u.likes);

By building up a Map in O(n), lookup gets O(1), thus the whole operation performs in O(n) + O(1 * n) = O(n).

I think two separate loops are better than nested loop

let array = [{ id:1, name: 'Adam', likes:2 },{ id:2, name: 'Ben', likes:3 },{ id:3, name: 'Cindy', likes:1 }];
let ids = array.reduce((acc, {id, name}) => (acc[id] = name, acc), {});
array.forEach(item => item.likes = ids[item.likes]);
console.log(array);

Use forEach and filter

let array = [{ id:1, name:' Adam', likes:2 },{ id:2, name: 'Ben', likes:3 },{ id:3, name: 'Cindy', likes:1 }];
array.forEach(function(e){
e.likes=array.filter(function(x){return x.id==e.likes})[0].name
})
console.log(array)

Related