Kirill Monocle Kirill Monocle - 1 month ago 7
Javascript Question

More elegant way to get filtered value?

I have a function that returns the filtered result based on string in the object (if it exist or not)

let foo = nodes.reduce((arr, cur) => {
cur.classes.split(' ').filter((el) => {
if (el === 'foo') arr.push(cur)
})
return arr;
}, []);


So it's just return all objects in array that contains 'foo' in classes object
This one, for example:

let nodes = [
{node: 'h1', classes: 'foo'},
{node: 'p', classes: 'bar'},
{node: 'p', classes: 'baz xxx'},
{node: 'h2', classes: 'bar baz foo'},
{node: 'ul', classes: 'poop foo'}
]


But my guts tells that the function possible to write more easily and succinctly. Any ideas?

Answer

You could use just Array#filter.

let nodes = [{node: 'h1', classes: 'foo'}, {node: 'p', classes: 'bar'}, {node: 'p', classes: 'baz xxx'}, {node: 'h2', classes: 'bar baz foo'}, {node: 'ul', classes: 'poop foo'}],
    foo = nodes.filter(a => a.classes.split(' ').some(b => b === 'foo'));

console.log(foo);

Comments