1

Let's say I have an array of id's const ids = [[1, 2, 3], [2, 3], [3]]

And have array with objects that have name for each id

const obj = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
  ];

What is the most proper way to get ids = [["One", "Two", "Three"], ["Two", "Three"], ["Three"]], I'm worrying that nested mapping could cause performance issues.

2 Answers 2

3

Use a combination of map and find. There may be a more performant way of doing it, but I'd suggest worrying about that only if you run into performance issues :-

const ids = [[1, 2, 3], [2, 3], [3]];

const obj = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
  ];

const mapped = ids.map(arr => arr.map(id => obj.find(obj => obj.id === id).name));
Sign up to request clarification or add additional context in comments.

Comments

1
const obj = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
  ];

const ids = [[1, 2, 3], [2, 3], [3]] ;

// dedicated object to keep association between id and names
let names = {} ;
obj.forEach( o => {
    names[ o.id ] = o.name ;
} ) ;

// map each sub array content to their real name
for( let i = 0; i <= ids.length-1; i++){
    ids[i] = ids[i].map( id => names[id] ) ;
}

console.log( ids ) ;

=>

[ [ 'One', 'Two', 'Three' ], [ 'Two', 'Three' ], [ 'Three' ] ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.