How to display all objects that contain all item from array - javascript

229 views Asked by At

Need for some help here. Looking for a hint to solve this issue :

The goal is to filter arrayOfObject and get all objects with the property fruits containing all the element from the given array.

  const arrayOfObject = [
  {
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 2,
    country: 'Canada',
    fruits: ["APPLE"]
  },
  {
    id: 3,
    country: 'France',
    fruits: ["ORANGE", "BANANA", "LEMON"]
  },
  {
    id: 4,
    country: 'Mexico',
    fruits: ["BANANA", "PYTHON", "CHERRY"]
  },
  {
    id: 5,
    country: 'Ukraine',
    fruits: ["APPLE", "ORANGE", "CHERRY"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
];

First exemple with this given array :

const firstArrayOfFruits = ["APPLE","ORANGE","BANANA"];

Should render =>

[
  {
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
]

Second exemple with this given array :

const secondArrayOfFruits = ["APPLE","ORANGE"];

Should render =>

[
  {
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 5,
    country: 'Ukraine',
    fruits: ["APPLE", "ORANGE", "CHERRY"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
]
2

There are 2 answers

5
Wais Kamal On BEST ANSWER

You can use Array.prototype.filter:

const arrayOfObject = [{
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 2,
    country: 'Canada',
    fruits: ["APPLE"]
  },
  {
    id: 3,
    country: 'France',
    fruits: ["ORANGE", "BANANA", "LEMON"]
  },
  {
    id: 4,
    country: 'Mexico',
    fruits: ["BANANA", "PYTHON", "CHERRY"]
  },
  {
    id: 5,
    country: 'Ukraine',
    fruits: ["APPLE", "ORANGE", "CHERRY"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
];

const firstArrayOfFruits = ["APPLE", "ORANGE", "BANANA"];

var arr = arrayOfObject.filter(item => item.fruits.filter(fruit => firstArrayOfFruits.indexOf(fruit) + 1).length >= firstArrayOfFruits.length);
console.log(arr);

0
robb On

Using ES6 some() function is useful because when finds an entry it will return true and doesnt check the rest, so you can save some calcs, time and CPU

const filtered = arrayOfObject.filter(obj => {
       if(obj.fruits.some(fruit => fruitsLisToCheck.includes(fruit)))
         return obj
    })

const fruitsLisToCheck = ['BANANA', 'APPLE'];

const arrayOfObject = [
  {
    id: 2,
    country: 'Canada',
    fruits: ["APPLE"]
  },
  {
    id: 3,
    country: 'France',
    fruits: ["BANANA"]
  },
  {
    id: 4,
    country: 'Mexico',
    fruits: ["CHERRY"]
  },
];