I need to create a new array by filtering the data.
{
"roles": [
{
"role": "manager",
"test_id": "123"
},
{
"role": "cashier",
"test_id": "123"
},
{
"role": "customer",
"test_id": "123"
},
{
"role": "cashier_2",
"test_id": "500"
}
],
}
I need to filter this array and create a new array by using the test_id
this is the expected format.
{
"roles": [
{
"role": [manager, cashier, customer],
"test_id": "123"
},
{
"role": "cashier_2",
"test_id": "500"
}
],
}
I tried using the filter method and using the map method but couldn’t get the expected output.
let x = [];
const test = userRoles?.map((item, index, element) => {
let next = element[index+1];
if(item?.test_id == next?.test_id){
x.push(item?.role)
}
})
3
Answers
I don’t think
map()
works here, as it just maps entries to (new) entries, but you need to group them. This is a job forreduce()
, which lets you create anything out of the entries.In this case, an object for easy lookup between
test_id
and grouped entries works well:To create the desired new array from the existing array, you can use the
reduce()
method to iterate through the roles and group them by theirtest_id
. For each role, you can check if there is already an object in the accumulator array with the sametest_id
. If there is, you can push the role to the existing object’srole
array. If there isn’t, you can create a new object with thetest_id
and an array containing the role, and push it to the accumulator array. Here’s some code that should do the trick:This should output:
Note that the code assumes that the
roles
array is already sorted bytest_id
. If that’s not the case, you can use thesort()
method to sort it first. Also, I’ve usedconsole.log()
to show the result, but you can return thegroupedRoles
array from a function or use it in some other way as needed.You could use
Object.entries()
in combination withArray#reduce()
andArray#map()
methods as follows: