'Filter items based on value in nested array
How do you filter the results using javascript so any item that includes the tag 'help' are excluded from the results?
Here is the object I get back and what I have so far, but obviously doesn't work:
const data = {
result: true,
items: [{
tags: ['typography', 'inspiration'],
title: 'Typefaces Inspired by the Bauhaus',
},
{
tags: ['layout', 'ratio', 'help'],
title: 'Building a combined CSS-aspect-ratio-grid',
},
]
}
const items = data.filter(data => data.tags !== 'help');
console.log(items)
Solution 1:[1]
You need to filter the data.items and use !some or !includes
Here is the data without the help in the items using includes
const data = {
result: true,
items: [{
tags: ['typography', 'inspiration'],
title: 'Typefaces Inspired by the Bauhaus',
},
{
tags: ['layout', 'ratio', 'help'],
title: 'Building a combined CSS-aspect-ratio-grid',
},
]
}
data.items = data.items.filter(item => !item.tags.includes('help'));
console.log(data)
Solution 2:[2]
data.items.filter(item=> !item.tags.some(tag => tag === 'help'))
some will return true if any tag equals 'help', so use filter to select item when some returns false
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mplungjan |
| Solution 2 | Janilson |
