javascriptarraysmap-functionfilterfunction

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


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"]
  }
]

Solution

  • 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);