Home > front end >  Array.find with Array.map in Javascript
Array.find with Array.map in Javascript

Time:11-18

I have two arrays, in the first one I store some user data. In the second, I store the basic data about the users.

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];

I wrote some simple code below:

const result = usersData.map(userData => {
    return {
        ...userData,
        userName: users.find(user => user.id === userData.userId).name
    }
})

After that, I get the result:

const result = [{ userId: 1, age: 18, name: "Alex" }];

The question is: how can you write this solution in a simpler way? Maybe should use the library "Lodash"?


Sorry, my English is not so good.

CodePudding user response:

For larger datasets, it's better to use a different data structure to increase the performance of the lookup and reduce the runtime.

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];
const usersById = Object.fromEntries(users.map(user => ([user.id, user])));

const result = usersData.map(userData => {
    return {
        ...userData,
        userName: usersById[userData.userId]?.name
    }
})

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

There is nothing simpler than this way, but you can optimise it so that you don't have to use find for every key. For that you can use Map here.

Note: If are trying to use any library, then under the hood they might be using the same method

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];

const usersDict = new Map();  // dictionary for users
users.forEach(o => usersDict.set(o.id, o));

const result = usersData.map(user => ({ ...user, username: usersDict.get(user.userId)?.name}))

console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related