Search code examples
javascriptarraysdata-structuresmappinglookup

Running a mapping task what is the correct 2nd array method for processing one of the newly created item's values?


I have an array containing objects:

let sportTag = [
    { id: 1, name: 'FOOTBALL', found: false },
    { id: 2, name: 'TENNIS'  , found: false },
    { id: 3, name: 'BASKET'  , found: false },
]

I have also have another array containing objects and for every object a field (sports) that is an array:

let person = [{
    id: 1,
    name: "Mark", 
    age: 23,
    sports: ["volleyball", "rugby", "tennis"],
}, {
    id: 2,
    name: "Rupert",
    age: 40,
    sports: ["golf"],
}, {
    id: 3,
    name: "John",
    age: 31,
    sports: ["football", "golf", "rugby", "tennis"],
}]

I would like to change sportTag found field to true when sportTag name is equal to every person sport. I tried with a nested map

const result = sportTag.map(st => {
    person.map(p => {
        p.sports.map(s => {
            if (st.name.toLocaleUpperCase() === s.toLocaleUpperCase()) {
                return {
                    ...st, found: true
                }
            }
            return s
        })
        return p
    })
    return st
})

console.log(sportTag)
//OUTPUT
// { id: 1, name: 'FOOTBALL', found: false },
// { id: 2, name: 'TENNIS'  , found: false },
// { id: 3, name: 'BASKET'  , found: false }
console.log(result)
//OUTPUT
// { id: 1, name: 'FOOTBALL', found: false },
// { id: 2, name: 'TENNIS'  , found: false },
// { id: 3, name: 'BASKET'  , found: false }

Why are the changes not reflected in the result? I expect the output to be:

{ id: 1, name: 'FOOTBALL', found: true  },
{ id: 2, name: 'TENNIS'  , found: true  },
{ id: 3, name: 'BASKET'  , found: false }

Solution

  • The problem with your code is that you are always returning st for each iteration of the first map, so you get the original values.

    You probably want something like this:

    const result = sportTag.map(st => {
        const foundSport = person.find(p => 
            p.sports.find(s => st.name.toLocaleUpperCase() === s.toLocaleUpperCase())
        );
        return foundSport
            ? { ...st, found: true }
            : st;
    });
    
    console.log(sportTag)
    // { id: 1, name: 'FOOTBALL', found: false },
    // { id: 2, name: 'TENNIS', found: false },
    // { id: 3, name: 'BASKET', found: false }
    console.log(result)
    // { id: 1, name: 'FOOTBALL', found: true },
    // { id: 2, name: 'TENNIS', found: true },
    // { id: 3, name: 'BASKET', found: false }