1

I have a data like this:

data: [
    {id: 1, name: 'device1', status: ['online','idle']},
    {id: 2, name: 'device2', status: ['network-error']},
    {id: 3, name: 'device3', status: ['online','idle']},
    {id: 4, name: 'device4', status: ['offline','inoperative']},
    
    ...
]

I'm trying to get distinct values of status in an array like this:

['online', 'idle', 'network-error', 'offline', 'inoperative']

I used this code:

let status = [...new Set(data.map(({deviceTags}) => deviceTags))];

But it returns:

[["online", "idle"], ["network-error"], ["online", "idle"], ["offline", "inoperative"]]

How can achieve distinct values of them?

1
  • 3
    result = [...new Set([your return array here].flat())] Commented Mar 5, 2021 at 13:38

1 Answer 1

4

Use .flatMap() instead of .map()

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.

const data = [
    {id: 1, name: 'device1', deviceTags: ['online','idle']},
    {id: 2, name: 'device2', deviceTags: ['network-error']},
    {id: 3, name: 'device3', deviceTags: ['online','idle']},
    {id: 4, name: 'device4', deviceTags: ['offline','inoperative']}
]

const status = [...new Set(data.flatMap(({deviceTags}) => deviceTags))];

console.log(status);

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

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.