javascript

Better way to filter an array of objects with one constant and one always changing value


I am currently looking for a better way to filter my array of objects to avoid duplicate my code again and again.

Here is my example array:

arr = [
{
"no": 11145,
"stringers": "P1",
"ribs": "R1",
"description": "some text"
},
{
"no": 14568,
"stringers": "P1",
"ribs": "R1",
"description": "some text"
},
{
"no": 24562,
"stringers": "P2",
"ribs": "R9",
"description": "some text"
},
{
"no": 658741,
"stringers": "P1",
"ribs": "R2",
"description": "some text"
},
{
"no": 325690,
"stringers": "P4",
"ribs": "R5",
"description": "some text"
},
{
"no": 9745201,
"stringers": "P1",
"ribs": "R2",
"description": "some text"
},
.....
]

Currently I am filtering the array like that:

let p1r1 = arr.filter(function(el){
  return el.stringers === "P1" && el.ribs === "R1"
})
let p1r2 = arr.filter(function(el){
  return el.stringers === "P1" && el.ribs === "R2"
})
// ...and so on

This results in a lot of lines where I repeat the same code over and over (except for the changing ribs value). Is there a more elegant way to solve this?


Solution

  • You could take an object as result with the wanted keys as groups.

    const
        data = [{ no: 11145, stringers: "P1", ribs: "R1", description: "some text" }, { no: 14568, stringers: "P1", ribs: "R1", description: "some text" }, { no: 24562, stringers: "P2", ribs: "R9", description: "some text" }, { no: 658741, stringers: "P1", ribs: "R2", description: "some text" }, { no: 325690, stringers: "P4", ribs: "R5", description: "some text" }, { no: 9745201, stringers: "P1", ribs: "R2", description: "some text" }],
        result = Object.groupBy(data, ({ stringers, ribs }) => stringers + ribs);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }