How can I extract all the numbers from this JSON in a set, in JavaScript?
[
{
"name": "list0",
"list": [0,1,2,3,4]
},
{
"name": "list1",
"list": [3,4,5,6,7,8,9]
}
]
I'd like to get a set with only:
0,1,2,3,4,5,6,7,8,9
How can I extract all the numbers from this JSON in a set, in JavaScript?
[
{
"name": "list0",
"list": [0,1,2,3,4]
},
{
"name": "list1",
"list": [3,4,5,6,7,8,9]
}
]
I'd like to get a set with only:
0,1,2,3,4,5,6,7,8,9
You can try using Set()
The
Setobject lets you store unique values of any type, whether primitive values or object references.
and flatMap()
The
flatMap()method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, butflatMap()is often quite useful, as merging both into one method is slightly more efficient.
var arr = [
{
"name": "list0",
"list": [0,1,2,3,4]
},
{
"name": "list1",
"list": [3,4,5,6,7,8,9]
}
]
var res = [... new Set(arr.flatMap(el => el.list))];
console.log(res);
you could use map and flat to iterate through the array and convert it to one level array or flatmap to do both at the same time and then you use Set to deduplicate
array=[ { "name": "list0", "list": [0,1,2,3,4] }, { "name": "list1", "list": [3,4,5,6,7,8,9] } ]
set=[...new Set(array.map(x=>x.list).flat())]
console.log(set)
using flatmap()
array=[ { "name": "list0", "list": [0,1,2,3,4] }, { "name": "list1", "list": [3,4,5,6,7,8,9] } ]
set=[...new Set(array.flatMap(x=>x.list))]
console.log(set)