Home > Mobile >  js object nested array filter based on array
js object nested array filter based on array

Time:05-26

const cars = [
    {
        brand: "Chevrolet",
        model: "Camaro",
        dates: (3) ['2022/05/28', '2022/06/02', '2022/06/05']
    },
    {
        brand: "Chevrolet",
        model: "Camaro",
        dates: (3) ['2022/05/30', '2022/06/02', '2022/06/05']
    },
    {
        brand: "Chevrolet",
        model: "Camaro",
        dates: (3) ['2022/05/28', '2022/06/01', '2022/06/05']
    }
]

I want to filter my object array based on another array

const arr2 = ["2022/06/02", "2022/06/05"];

I want to get results like that;

[
   {
     brand: "Chevrolet",
     model: "Camaro",
     dates: (3) ['2022/05/28', '2022/06/02', '2022/06/05']
   },
   {
     brand: "Chevrolet",
     model: "Camaro",
     dates: (3) ['2022/05/30', '2022/06/02', '2022/06/05']
   }
]

I used includes

let filtered = cars.filter((item) => item.dates.includes(arr2))

I got empty array.

when I pass a string to in includes I got filtered array.

let filtered = cars.filter((item) => item.dates.includes("2022/06/02"))

No I need to compare arr2. Its' length could be changed.

How can I pass an array to cars.include() function

CodePudding user response:

[{}, {}].includes({})

returns false because it compares objects by object reference, not values in the object, so it's equivalent to

const a = {}; // new, empty object
const b = {}; // a different new, empty object
const c = {}; // yet another new, empty object
const answer = [a, b].includes(c) // false

Also, arrays are objects!

So that's why, when you pass an object (whether or not it's an array) into Array.prototype.includes, it returns false unless that same object is an element of the array.

You probably want something like this:

// Function that returns true if two arrays intersect
const includesAny = (arr1, arr2) => arr1.some(e1 => arr2.includes(e1));

const filterCarsByDates = (
  datesSought => cars.filter(
    car => includesAny(
      cars.dates,
      datesSought
    )
  )
);

CodePudding user response:

let cars = [
    {
        brand: "Chevrolet",
        model: "Camaro",
        dates: ['2022/05/28', '2022/06/02', '2022/06/05']
    },
    {
        brand: "Chevrolet",
        model: "Camaro",
        dates: ['2022/05/30', '2022/06/02', '2022/06/05']
    },
    {
        brand: "Chevrolet",
        model: "Camaro",
        dates: ['2022/05/28', '2022/06/01', '2022/06/05']
    }
];
    
let arr2 = ["2022/06/02", "2022/06/05"];

// A method that checks if `src` array contains all elements of `target` array
let checker = (src, target) => target.every(v => src.includes(v));  

let filtered = cars.filter((item) => checker(item.dates, arr2));  

console.log(filtered);

  • Related