0

I apologize in advance, couldn't come up with a better example for data.

So I have the array things, which currently just consists of objects that contain an id property and an array which just contains random things/words I could suddenly come up with, and other_things, with with some random words from things array.

let things=[
  {
    id: 1,
    names: ['car','door','chair']
  },
  {
    id: 2,
    names: ['cat','dog','door']
  },
  {
    id: 3,
    names: ['phone','mouse','cat']
  },
  {
    id: 4,
    names: ['building','desk','pen']
  },
  {
    id: 5,
    names: ['road','date','number']
  }
];

let other_things=['car','door','pen'];

What I'd like to achieve is to filter array things, and only get those objects/elements, where the names array contains at least one element from the other_things array.

In this example, only things[2] and things[4] have no matches with any words from other_things, so we don't need them.

I have already tried many things, like combining ES6 methods, like filter, every or map, tried using nested for loops, but nothing has worked out for me unfortunately.

2
  • 1
    const other = { car: true, door: true, pen: true }; /* can be generated from array */ let result = things.filter(({ names }) => names.some(e => other[e] ?? false )); If your items aren't strings, use a Map instead, or just do something cheap like includes or indexOf on ither_things directly, if you only have a couple dozen or hundred items at best. Commented Jan 3, 2021 at 13:52
  • Tbh, for the structure to check, even a Set should be enough, you don't care about insertion order or anything. Commented Jan 3, 2021 at 14:01

1 Answer 1

3

let things=[
  {
    id: 1,
    names: ['car','door','chair']
  },
  {
    id: 2,
    names: ['cat','dog','door']
  },
  {
    id: 3,
    names: ['phone','mouse','cat']
  },
  {
    id: 4,
    names: ['building','desk','pen']
  },
  {
    id: 5,
    names: ['road','date','number']
  }
];

let other_things=['car','door','pen'];

console.log(things.filter(t => t.names.filter(n => other_things.includes(n)).length > 0))

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.