0

Is there a built in Javascript function or library to do the following:

const data = [
    { name: 'name1', type: 'type1' },
    { name: 'name2', type: 'type2' },
    { name: 'name3', type: 'type3' },
    { name: 'name4', type: 'type2' },
];

To search the following and return all objects where type = 'type2'

Something similar to data.findIndex((i) => i.type === 'type2') but returns all matches rather than first index?

Thanks

1

2 Answers 2

9

You are looking for Array.filter():

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Example:

const data = [
    { name: 'name1', type: 'type1' },
    { name: 'name2', type: 'type2' },
    { name: 'name3', type: 'type3' },
    { name: 'name4', type: 'type2' },
]

const result = data.filter(o => o.type === 'type2')

console.log(result)

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

Comments

1

You can use filter()

const data = [
    { name: 'name1', type: 'type1' },
    { name: 'name2', type: 'type2' },
    { name: 'name3', type: 'type3' },
    { name: 'name4', type: 'type2' },
];
let res = data.filter(({type}) => type === "type2");
console.log(res)

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.