Search code examples
javascriptarraysjavascript-objects

How to relate objects by name and column


I am in doubt about the following situation, so please, check the following array of objects:

 let arrayQualityRated = [{
     name: "Jande",
     col: 4
 }, {
     name: "Good",
     col: 4
 }, {
     name: "Good",
     col: 4
 }, {
     name: "Bad",
     col: 4
 }, {
     name: "Elmo",
     col: 2
 }, {
     name: "Bad",
     col: 2
 }, {
     name: "Tiago",
     col: 3
 }, {
     name: "Bad",
     col: 3
 }];

I want to do some like filter based on the name and col keys.

But I need to do dynamically, so from what I understand, look for the keys "name" based on the following array:

let persons = ["Jande", "Elmo", "Tiago"]

I hope I have been clear about my doubt. I'm counting on your patience and help! :)

I expect output like that:

[   
    {
        name: "Jande",
        col: 4
    },
    {
        name: "Good",
        col: 4
    },
    {
        name: "Bad",
        col: 4
    },
    {
        name: "Good",
        col: 4
    }

],

[   
    {
        name: "Elmo",
        col: 2
    },
    {
        name: "Bad",
        col: 2
    }

],

[   
    {
        name: "Tiago",
        col: 3
    },
    {
        name: "Bad",
        col: 3
    }

]

Briefly, I want an individual array of objects based on the string "person name" (that based in array "persons") and "col".


Solution

  • I think it's not a simple filter, as the result is expected in three different arrays. I'd use map() and then filter(), as the col value is dynamic (can't tell before you identify the person by name).

    Have a look at the resulting array - it has the structure you were asking for.

    let arrayQualityRated = [{
      name: "Jande",
      col: 4
    }, {
      name: "Good",
      col: 4
    }, {
      name: "Good",
      col: 4
    }, {
      name: "Bad",
      col: 4
    }, {
      name: "Elmo",
      col: 2
    }, {
      name: "Bad",
      col: 2
    }, {
      name: "Tiago",
      col: 3
    }, {
      name: "Bad",
      col: 3
    }];
    
    let persons = ["Jande", "Elmo", "Tiago"]
    
    const classifyArrayItems = (persons, arrayQualityRated) => {
      // mapping the array, so it has all the persons
      return persons.map(person => {
        // first find the col number corresponding to the
        // person in the array
        const col = arrayQualityRated.find(e => e.name === person).col
        // return all the objects that have the same
        // col value
        return arrayQualityRated.filter(e => e.col === col)
      })
    }
    
    console.log(classifyArrayItems(persons, arrayQualityRated))