0

I can't figure it out how to set a filter that compares an array of objects with an array. I don't even know if it is possible. Here is a bit of the data and what I'm attempting to do:

The filters come from a number of checkboxes in my ui. Below and example:

the strings are characteristics and the number is the height.

const filter = ["moto", "gre", "sm"]
const arrayOfData = [{id: 1, characteristics: ['motorbike', 'green', 'small'],

}, {id: 2, characteristics: ['car', 'large', 'black']}, {id: 3, characteristics: ['motorbike', 'yellow', 'large']]


The result should throw those which arrays contain the initial letter, in the case above. I have tried using some() and include() but I can't work it out!

2
  • please add your code so we know where you got stuck Commented Jan 17, 2021 at 13:15
  • something like arr.find(item=>loop_through_its_content_and_check_it_match_the_prefix(filter,item.char)) Commented Jan 17, 2021 at 13:17

1 Answer 1

1

You could do it combination of array Array.prototype.filter() as well as Array.prototype.some() method and check prefix with String.prototype.startsWith() method.

const arrayOfData = [
  { id: 1, characteristics: ['motorbike', 'green', 'small'] },
  { id: 2, characteristics: ['car', 'large', 'black'] },
  { id: 3, characteristics: ['motorbike', 'yellow', 'large'] },
];

const filter = ['moto', 'gre', 'sm'];
const ret = arrayOfData.filter(
  (x) =>
    x.characteristics.filter((y) => filter.some((z) => y.startsWith(z)))
      .length > 0
);
console.log(ret);

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

1 Comment

Thanks! This is what I was looking for and actually made me realise that I have a problem with my data. As you see, it throws small and medium, I need to change this, but thanks for the push!

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.