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?
2
Answers
You can use array map to get just the ribs value.
A set is like an array, but only of unique values.
I like using array functions, so I cast that back to an array
Now we can do anything with that.
Runnable example:
You could take an object as result with the wanted keys as groups.