0

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
1

4 Answers 4

3

You can try using Set()

The Set object 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, but flatMap() 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);

Sign up to request clarification or add additional context in comments.

Comments

3

You can use array.reduce and spread operator:

let input = [
  {
    "name": "list0",
    "list": [0,1,2,3,4]
  },
  {
    "name": "list1",
    "list": [3,4,5,6,7,8,9]
  }
];

let numbers = input.reduce((acc,cur) => [...acc, ...cur.list], []);
console.log(numbers);

console.log(...new Set(numbers))

Comments

2

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)

Comments

2

You can use the spread ...array operator to solve the problem.

let arr = [
  {
    "name": "list0",
    "list": [0,1,2,3,4]
  },
  {
    "name": "list1",
    "list": [3,4,5,6,7,8,9]
  }
] 

let a = [];
arr.forEach(obj=>{
    a.push(...obj.list)
})

const set = new Set([...a]);
console.log(...set)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.