2

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?

Harry
  • 41
  • 1
  • 6
  • 3
    Cant you store (id,name) in a hashmap. https://stackoverflow.com/questions/8877666/how-is-a-javascript-hash-map-implemented – Hemant Oct 17 '19 at 05:46

3 Answers3

5

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).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • should be `new Map(array.map(u => [u.id, u.name]));` OR `u.likes = byID.get(u.likes).name` – AZ_ Oct 17 '19 at 06:21
  • @AZ_ I wrote that before the OPs edit, and interpreted `likes: Adam` as a reference. I'll leave it as is, thanks for the comment :) – Jonas Wilms Oct 17 '19 at 08:21
2

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);
Bravo
  • 6,022
  • 1
  • 10
  • 15
0

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)
ellipsis
  • 12,049
  • 2
  • 17
  • 33