Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active February 23, 2024 12:59
Show Gist options
  • Save jherax/f11d669ba286f21b7a2dcff69621eb72 to your computer and use it in GitHub Desktop.
Save jherax/f11d669ba286f21b7a2dcff69621eb72 to your computer and use it in GitHub Desktop.
Filters an array of objects with multiple match-criteria.
/**
* Filters an array of objects using custom predicates.
*
* @param {Array} array: the array to filter
* @param {Object} filters: an object with the filter criteria
* @return {Array}
*/
function filterArray(array, filters) {
const filterKeys = Object.keys(filters);
return array.filter(item => {
// validates all filter criteria
return filterKeys.every(key => {
// ignores non-function predicates
if (typeof filters[key] !== 'function') return true;
return filters[key](item[key]);
});
});
}
/**
* The method `filterArray()` has the following signature:
*
* `function filterArray<TInput = any>(array: TInput[], filters: IFilters) => TInput[]`
*
* Where the function receives an array as the first argument, and a plain object
* describing the fields to filter as the last argument.
* The function returns an array of the same type as the input array.
*
* The signature of the filters arguments is the following:
*
* `interface IFilters {
* [key: string]: (value: any) => boolean;
* }`
*
* Where the `filters` argument is an object that contains a `key: string`
* and its value is a function with the value of the property to evaluate.
* As the function predicate is evaluated using the `Array.prototype.every()` method,
* then it must return a boolean value, which will determine if the item
* must be included or not in the filtered array.
*/
describe('Testing filterArray()', () => {
it('should filter an array of objects by custom predicates', () => {
const products = [
{ name: 'A', color: 'Blue', size: 50, locations: ['USA', 'Europe'], details: { length: 20, width: 70 } },
{ name: 'B', color: 'Blue', size: 60, locations: [], details: { length: 20, width: 70 } },
{ name: 'C', color: 'Black', size: 70, locations: ['Japan'], details: { length: 20, width: 71 } },
{ name: 'D', color: 'Green', size: 50, locations: ['USA'], details: { length: 20, width: 71 } },
];
const filters = {
size: size => size === 50 || size === 70,
color: color => ['blue', 'black'].includes(color.toLowerCase()),
locations: locations => locations.find(x => ['JAPAN', 'USA'].includes(x.toUpperCase())),
details: details => details.length < 30 && details.width >= 70,
};
const filters = {
size: (size) => size === 50 || size === 70,
color: (color) => ['blue', 'black'].includes(color.toLowerCase()),
details: (details) => details.length < 30 && details.width >= 70,
locations: (locations) => {
if (locations.includes('USA')) return true; // case sensitive
if (locations.includes('Japan')) return true; // case sensitive
const url = window.location.pathname.toLowerCase();
if (url.includes('/en-us/')) return true; // not case sensitive
if (url.includes('/es/')) return true; // not case sensitive
return false;
}
};
const filtered = filterArray(products, filters);
const expected = [
{ name: 'A', color: 'Blue', size: 50, locations: ['USA', 'Europe'], details: { length: 20, width: 70 } },
{ name: 'C', color: 'Black', size: 70, locations: ['Japan'], details: { length: 20, width: 71 } },
];
expect(filtered).toStrictEqual(expected);
});
});
// ignores case-sensitive
const getValue = value => (typeof value === 'string' ? value.toUpperCase() : value);
/**
* Filters an array of objects (one level-depth) with multiple criteria.
*
* @param {Array} array: the array to filter
* @param {Object} filters: an object with the filter criteria
* @return {Array}
*/
function filterPlainArray(array, filters) {
const filterKeys = Object.keys(filters);
return array.filter(item => {
// validates all filter criteria
return filterKeys.every(key => {
// ignores an empty filter
if (!filters[key].length) return true;
return filters[key].find(filter => getValue(filter) === getValue(item[key]));
});
});
}
describe('Testing filterPlainArray()', () => {
it('should filter an array of objects with one level-depth', () => {
const products = [
{ name: 'A', color: 'Blue', size: 50 },
{ name: 'B', color: 'Blue', size: 60 },
{ name: 'C', color: 'Black', size: 70 },
{ name: 'D', color: 'Green', size: 50 },
];
const filters = {
color: ['BLUE', 'black'],
size: [70, 50],
};
const filtered = filterPlainArray(products, filters);
const expected = [
{ name: 'A', color: 'Blue', size: 50 },
{ name: 'C', color: 'Black', size: 70 },
];
expect(filtered).toStrictEqual(expected);
});
});
@estherjsuh
Copy link

@jherax It works! Thanks a bunch!!

@estherjsuh
Copy link

@jherax Hi again,
After some testing, I realized that the code isn't filtering as expected.

//Expected - OR within same filter groups:
filters={
categories: ['women', 'men']  => 'women' === true || 'men' === true
   &&
prices: ['oneDollar', 'twoDollar'] => 'oneDollar' === true ||  'twoDollar' === true
    &&
cities:['new-york'] => ['new-york'].includes(obj.nearestLocation)
}
//What I am getting - AND within same filter groups:

filters={
categories: ['women', 'men']  => 'women' === true  && 'men' === true
   &&
prices: ['oneDollar', 'twoDollar'] => 'oneDollar' === true && 'twoDollar' === true
    &&
cities:['new-york'] => ['new-york'].includes(obj.nearestLocation)
}

@PhillipUg
Copy link

First of all thanks a lot for this solution guys. But I found it wasn't returning the desired results when I used includes and indexOf. So I made a small tweak (used === instead) and it worked like a charm for me. Coz what i was doing initially was evaluating to something like: return "PETER".includes("PETER") same thing for indexOf. so the results were inaccurate for me.

const multiFilter = (arr, filters) => {
  let filterKeys = Object.keys(filters);
  return arr.filter(eachObj => {
    return filterKeys.every(eachKey => {
      if (!filters[eachKey].length) {
        return true; // passing an empty filter means that filter is ignored.
      }
      return filters[eachKey] === (eachObj[eachKey]);
    });
  });
};

@jamaljeantobias
Copy link

Thanks for this!

@afatoga
Copy link

afatoga commented Feb 15, 2021

did anyone try to count how many "hits" there is for each filter ?

Example
colors:
green (20), blue (2)

shapes:
round (1), other (0)


I am using this snippet:

  const result = data.filter(eachObj => {
      return filterKeys.every(eachKey => {
        if (!filters[eachKey].length) {
          return true; // passing an empty filter means that filter is ignored.
        }
        return filters[eachKey].includes(eachObj[eachKey]);
      });
    });

@david2vicente
Copy link

Hello there, thanks for those examples guys. I'm still struggling with my case...

Here is my data :

const data = [
    {
      "id": 2,
      "name": "Dos rond dos creux",
      "exercise_bodyParts": [{"bodyPart": {"id": 2, "name": "Dos"}}, {"bodyPart": {"id": 7, "name": "Hanches"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}, {"equipment": {"id": 2}}]
    },
    {
      "id": 3,
      "name": "Superman",
      "exercise_bodyParts": [{"bodyPart": {"id": 2, "name": "Dos"}}, {"bodyPart": {"id": 6, "name": "Bassin"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}]
    }

Here is my filter object

const filter = {
    exercise_bodyParts: [2,7], // can be empty or whatever values
    exercise_equipments: [2] // can be empty or whatever values
  }

Expected result :

const filteredData = [
    {
      "id": 2,
      "name": "Dos rond dos creux",
      "exercise_bodyParts": [{"bodyPart": {"id": 2, "name": "Dos"}}, {"bodyPart": {"id": 7, "name": "Hanches"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}, {"equipment": {"id": 2}}]
    }
]

For now, i was able to filter only one by one and not all together my filters like this :

data.filter((element) => element.exercise_bodyParts.some((subElement) => filter.exercise_bodyParts.includes(subElement.bodyPart.id)))
OR
data.filter((element) => element.exercise_equipments.some((subElement) => filter.exercise_equipments.includes(subElement.equipment.id)))

I've tried to use a generic function to loop through the filter object like you did @jherax with no success... :(

Any ideas how to achieve this ?

Thanks!

@twalow
Copy link

twalow commented Feb 21, 2021

@david2vicente
Filter removes data.
Are you trying to remove or keep? Because looking at your starting array and desired result it appears your filter object is not a filter but what rather what you're trying to keep.

Another question:
exercise_bodyParts: [2,7], // can be empty or whatever values
exercise_equipments: [2] // can be empty or whatever values

Do you want to keep any given data[x] for where all of these properties exist?
ie., you have 2 properties: bodyParts and equipments. does that data have to include all of properties and all those specific ids for it to be returned?

@twalow
Copy link

twalow commented Feb 21, 2021

@david2vicente

If I'm guessing correctly this is what you need. If it's not all, I'm sure you can adjust this to get what you want:

(() => {

const data = [
    {
      "id": 2,
      "name": "Dos rond dos creux",
      "exercise_bodyParts": [{"bodyPart": {"id": 2, "name": "Dos"}}, {"bodyPart": {"id": 7, "name": "Hanches"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}, {"equipment": {"id": 2}}]
    },
    {
      "id": 3,
      "name": "Superman",
      "exercise_bodyParts": [{"bodyPart": {"id": 2, "name": "Dos"}}, {"bodyPart": {"id": 6, "name": "Bassin"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}]
    }
];

const keepers = {
    exercise_bodyParts: [2, 7],
    exercise_equipments: [2]
};

const result = data.reduce((a, b) => {
    
    const body_part_ids = b.exercise_bodyParts.map((obj) => {
        return obj.bodyPart.id;
    });

    const exercise_equipment_ids = b.exercise_equipments.map((obj) => {
        return obj.equipment.id;
    });

    const has_body_parts = keepers.exercise_bodyParts.every((a) => {
        return body_part_ids.includes(a);
    });

    const has_equipments = keepers.exercise_equipments.every((a) => {
        return exercise_equipment_ids.includes(a);
    });

    return (has_body_parts && has_equipments) ? [...a, b] : a;


}, []);

console.log(result);

})();

@david2vicente
Copy link

Hello @twalow, many thanks, you were guessing right, i want to keep exercises according to id passed in the keepers object 👍 We are very close to what i'm trying to achieve : how can i return exercises with bodypart id equal to "2" OR "7" and not "2" AND "7". And between bodypart and equipment, its an AND rule..

I'll give an another example for a better understanding 😄

const data = [
   {
      "id": 1,
      "name": "Random name",
      "exercise_bodyParts": [{"bodyPart": {"id": 2, "name": "Dos"}}, {"bodyPart": {"id": 9, "name": "Epaules"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}, {"equipment": {"id": 2}}]
    },
    {
      "id": 2,
      "name": "Dos rond dos creux",
      "exercise_bodyParts": [{"bodyPart": {"id": 2, "name": "Dos"}}, {"bodyPart": {"id": 7, "name": "Hanches"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}, {"equipment": {"id": 2}}]
    },
    {
      "id": 3,
      "name": "Superman",
      "exercise_bodyParts": [{"bodyPart": {"id": 1, "name": "Psoas"}}, {"bodyPart": {"id": 6, "name": "Bassin"}}],
      "exercise_equipments": [{"equipment": {"id": 1}}]
    }
];

const keepers = {
    exercise_bodyParts: [1, 2, 7],
    exercise_equipments: [1]
}; 
// Would return exercise 1, 2 and 3

const keepers = {
    exercise_bodyParts: [2, 6, 9],
    exercise_equipments: [2]
}; 
// Would return exercise  1 and 2

const keepers = {
    exercise_bodyParts: [],
    exercise_equipments: []
}; 
// Would return all the exercises

I hope my example is better...

@twalow
Copy link

twalow commented Feb 21, 2021

So it's a fairly simple adjustment.

Before I was using "every", which means ALL. But you're content if there's just ONE match, which "some" does.

As for your empty arrays that's a different problem., because if you're saying keepers is [] you're saying nothing is a keeper. That is why you have to build this exception into the function prior to running anything.

Which should be fairly simple.

const get_keepers = (data, keepers) => {

    // handles exception of when both arrays are empty
    if (keepers.exercise_bodyParts.length === 0 && keepers.exercise_equipments.length === 0) {
        return data.reduce((a, b) => [...a, b], []);
    }

    // returns keepers
    return data.reduce((a, b) => {
    
        const body_part_ids = b.exercise_bodyParts.map((obj) => {
            return obj.bodyPart.id;
        });

        const exercise_equipment_ids = b.exercise_equipments.map((obj) => {
            return obj.equipment.id;
        });
    
        const has_body_parts = keepers.exercise_bodyParts.some((a) => {
            return body_part_ids.includes(a);
        });
    
        const has_equipments = keepers.exercise_equipments.some((a) => {
            return exercise_equipment_ids.includes(a);
        });
    
        return (has_body_parts && has_equipments) ? [...a, b] : a;

    }, []);

};

console.log(get_keepers(data, keepers));

@twalow
Copy link

twalow commented Feb 21, 2021

Granted I could have made this code significantly shorter and more compact using tricks,. but I highly recommend readable code over fancy code. Code should read like a book. :D

@david2vicente
Copy link

david2vicente commented Feb 22, 2021

Thanks @twalow for the update!! I've tried the "some" method before without success. It seems if "exercises_bodyParts" or "exercise_equipments" in "keepers" is empty, the returned object is empty. I forgot to specify one example for you and it's my fault...sorry.

const keepers = {
    exercise_bodyParts: [2],
    exercise_equipments: []
}; 
// would return exercise 1 and 2.

@nageshwari17
Copy link

nageshwari17 commented Apr 20, 2021

Hi Guys , Can any one help me with below scenario please

const arr = {
  "red": {
    "FF0000": [
      {
        "color": "red",
        "color_info": [
          {
            "color_code": "FF0000",
            "color_desc": "describe"
          },
          {
            "color_code": "FF6347",
            "color_desc": "tomato"
          }
        ]
      },
     {
        "color": "yellow",
        "color_info": [
          {
            "color_code": "FF0000",
            "color_desc": "describe"
          },
          {
            "color_code": "FF6347",
            "color_desc": "tomato"
          }
        ]
      }
    ],
    "FF6347": [
      {
        "color": "red",
        "color_info": [
          {
            "color_code": "FF0000",
            "color_desc": "describe"
          },
          {
            "color_code": "FF6347",
            "color_desc": "tomato"
          }
        ]
      }
    ],
  }
}

by referring above JOSN I need get below output

const output = [
 {
        "color": "red",
        "color_info": [
          {
            "color_code": "FF0000",
            "color_desc": "describe"
          }
        ]
      },
      {
        "color": "red",
        "color_info": [
          {
            "color_code": "FF6347",
            "color_desc": "tomato"
          }
        ]
      }
    ]

kind of ungrouping the data based on color code.
Please help me what kind of approach need to use.

Thank you.

@twalow
Copy link

twalow commented Apr 21, 2021

I don't mind helping but you guys need to actually put effort into what you want. I'm not interested in spending my time coding out 10 different variations guessing what you ultimately want.

Your example does not account for multiple things. One obvious omission is the color yellow. Where did that go in your output? Will it always be two objects per color_info? Does "red" and "FF0000" go away? Are there other keys like "red" & "FF0000". Provide multiple examples and expectations of what you expect the result to be.

@LupusX5
Copy link

LupusX5 commented Jun 13, 2021

Hello guys! Thank God I found this thread! You are saving lives!
By the way, when applying the filter, I run into the following problem: I have the price list (json file) where the prices are stored. When filtering by price, the filter ignores floating numbers. Could you tell please how to fix it?
So my json looks like this:

const hotels = [
{"id":1, "name": "4 Seasons", "price":120.70, "currency":"USD", "country":"Canada"}
{"id":2, "name": "Triton palm", "price":112, "currency":"USD", "country": "Canada"}
{"id":3, "name": "Herrington place", "price":180, "currency":"USD", "country": "Poland"}
}]

I tried to modify the filter like that:

function range(start, end) {
  start = parseFloat(start);
  end = parseFloat(end);
  return new Float32Array(end - start).fill().map((d, i) => i + start);
}

But it led me to nowhere :(

Full code I have:

const array = data;
const filterData = {
  country: ["Canada"],
  price: range(100,150)
};

function filterPlainArray(array, filters) {
  const getValue = value => (typeof value === 'string') ? value.toUpperCase() : value;
  const filterKeys = Object.keys(filters);

  return array.filter(item => {
    // validates all filter criteria
    return filterKeys.every(key => {
      // ignores an empty filter
      if (!filters[key].length) return true;
      return filters[key].find(filter => getValue(filter) === getValue(item[key]));
    });
  });
}

const filteredList = filterPlainArray(array, filterData);
console.log(filteredList);

@d4rkness-com
Copy link

d4rkness-com commented Jun 13, 2021

(() => {

const hotels = [
  {"id":1, "name": "4 Seasons", "price":120.70, "currency":"USD", "country":"Canada"},
  {"id":2, "name": "Triton palm", "price":112, "currency":"USD", "country": "Canada"},
  {"id":3, "name": "Herrington place", "price":180, "currency":"USD", "country": "Poland"}
];

const keep_these_hotels = {
  country: ['Canada'],
  price: { min: 100, max: 150 }
};

const filter_function = (hotels) => {
  return hotels.filter((hotel) => {
    return Object.keys(keep_these_hotels).some((key) => {
      if (key === 'country'){
        return keep_these_hotels.country.some((country) => country === hotel.country);
      }
      if (key === 'price'){
        return hotel.price >= keep_these_hotels.price.min && hotel.price <= keep_these_hotels.price.max;
      }
    });
  })
}

console.log(filter_function(hotels));

})();

// The keep_these_hotels doesnt require for all conditions to be met, just one of them. Since you didn't mention that part I'm assumed it this way.

@elharmouchiA
Copy link

elharmouchiA commented Sep 3, 2021

hello
thank you guys,
i have a small problem with this function

filterPlainArray(array, filters) { const filterKeys = Object.keys(filters); return array.filter(item => { // validates all filter criteria return filterKeys.some(key => { // ignores an empty filter if (!filters[key].length) return true; return filters[key](filter => filter === item[key]); }); }); }

when i set filters like this

var filterData = { typeTraitement:[0], typeExecution:[0], };

and
var dataArray =[ {"typeTraitement":0, "typeExecution": 1} {"typeTraitement":1, "typeExecution": 0} {"typeTraitement":2, "typeExecution": 0} }]

the result is null and is happing only win i filter with 0 the others values is correct
some one has any idea why this happing
thank you for help

@shawn-fullbay
Copy link

Is it too hard to ask to give us a working example?

return filters[key](filter => filter === item[key]); }); }); } is not even valid syntax.

@elharmouchiA
Copy link

elharmouchiA commented Sep 4, 2021

Is it too hard to ask to give us a working example?

return filters[key](filter => filter === item[key]); }); }); } is not even valid syntax.

thank you pro
I'm using TypeScript
here the syntax of function

filterPlainArray
    
filterPlainArray(array, filters){
const filterKeys = Object.keys(filters);
return array.filter(item => {
    return filterKeys.some(key => {
      if (!filters[key].length) return true;
      return filters[key].find(filter => filter === item[key]);
    });
  });
}
   
  
filtres data is filtres
    
var filters = { typeTraitement:[0], typeExecution:[0], };
   
  

and

dataArray
    
var dataArray =[ {"typeTraitement":0, "typeExecution": 1},
 {"typeTraitement":1, "typeExecution": 0} ,
{"typeTraitement":2, "typeExecution": 0},
{"typeTraitement":2, "typeExecution": 3} }];
   
  
result -result is empty-
    
var result=this.filterPlainArray(dataArray ,filters );
   
  
expected result is
    
[ {"typeTraitement":0, "typeExecution": 1},
 {"typeTraitement":1, "typeExecution": 0} ,
{"typeTraitement":2, "typeExecution": 0} }]
   
  

remark
the function work fine with any number in filters other than 0

@rcdegoma
Copy link

rcdegoma commented Sep 27, 2021

Question: What if the Value are multiple that is delimited by semicolon ";",

Sample Data :
Title multi value = "Station 1;Station 2"
Filter State = Station 1 //This is the user selected in a multi checkbox option

  const filterKeys = Object.keys(filters);
  return arr.filter(eachObj => {
    return filterKeys.every(eachKey => {
      if (!filters[eachKey].length) {
        return true; // passing an empty filter means that filter is ignored.
      }
      **return filters[eachKey].includes(eachObj[eachKey]);** 
      // The current behaviour, it only retrieves the exact data sample is "Station 1"= "Station 1"
    });
  });
};

@mohdatique
Copy link

mohdatique commented Mar 18, 2022

@jherax -Great, thanks for this brainstorming thread.
I am struggling with nested keys in json to compare dynamically.

my data

 {
      "id": 1,
      "user_status": "ACTIVE",
      "roles": [{"id": "APP_ADMIN", "name": "App Admin"}, {"APP_USER": , "name": "App User"}],
       "permissions": {"apps": ["abc", "pqr"]}
    },

I am currently filtering it by user_status because it is straightforward, but need your help to make dynamic condition for roles and apps which is inside permission. How i can create condition for apps and roles.

@refundr
Copy link

refundr commented Mar 18, 2022

@jherax - I can't ever shake your hand - but please accept this thank you so much for sharing this !
Cheers to writing better code with fewer headaches !

@MohdKamranAlam
Copy link

Hi foks, I am creating 2 level depth filtering(multi select check box) and need to filter out
image

  • could you please suggest me the code.

@MohdKamranAlam
Copy link

MohdKamranAlam commented May 12, 2022

  • This is my filter file:
    image

Hi foks, I am creating 2 level depth filtering(multi select check box) and need to filter out image

  • could you please suggest me the code.

@rakathal
Copy link

rakathal commented Aug 17, 2022

Consider I have the below data:

[
{
    apId: "c3:89:6f:1a:83:5e",
    description: "Kiruna Ramp Beacon",
    estimated: false,
    externalId: null,
    id: 718311,
    name: "BLE_1",
    posX: 6622.404970932526,
    posY: 2834.686893101607,
    posZ: 3012.490824884788,
    timestamp: 0,
    type: "BLE_BEACON"
},
{
    apId: "e4:97:29:25:41:73",
    description: "Kiruna Ramp Beacon",
    estimated: false,
    externalId: null,
    id: 718312,
    name: "BLE_2",
    posX: 6401.213050968167,
    posY: 2791.9930699182455,
    posZ: 2983.5542385630656,
    timestamp: 0,
    type: "BLE_BEACON"
},
{
    apId: "ce:76:58:8c:66:e1",
    description: "Kiruna Ramp Beacon",
    estimated: false,
    externalId: null,
    id: 718313,
    name: "BLE_3",
    posX: 6175.356128422606,
    posY: 2863.5582614152468,
    posZ: 2956.701987555463,
    timestamp: 0,
    type: "BLE_BEACON"
}
]

Expected output is:

[
{
    apId: "c3:89:6f:1a:83:5e",
    description: "Kiruna Ramp Beacon",
    name: "BLE_1",
    posX: 6622.404970932526,
    posY: 2834.686893101607,
    posZ: 3012.490824884788,
    type: "BLE_BEACON",
},
{
    apId: "e4:97:29:25:41:73",
    description: "Kiruna Ramp Beacon",
    name: "BLE_2",
    posX: 6401.213050968167,
    posY: 2791.9930699182455,
    posZ: 2983.5542385630656,
    type: "BLE_BEACON",
},
{
    apId: "ce:76:58:8c:66:e1",
    description: "Kiruna Ramp Beacon",
    name: "BLE_3",
    posX: 6175.356128422606,
    posY: 2863.5582614152468,
    posZ: 2956.701987555463,
    type: "BLE_BEACON"
}
]

How to do it in TypeScript?

@klayus
Copy link

klayus commented Sep 29, 2022

hey man! thank you a million!!! if you ever come to romania i'll buy you 10 beers!!!!!!!!!!!!!!!!!!!

@elpahlevi
Copy link

Hey dude, thanks for sharing! Your snippet is handy so I can solve my problem related to filtering data using multiple criteria

@MLS535
Copy link

MLS535 commented Jan 16, 2023

Great code!
@estherjsuh where you able to solve it? I have the same problem....

@circa10a
Copy link

I made a small lib to solve this problem
https://github.com/circa10a/filter-object-array

@AshrafulIslam2
Copy link

AshrafulIslam2 commented Feb 7, 2023

I have an array of Sizes which is Size = ["40","XL","43","M"]
This is what my Products JSON File looks like :

[{
    "productCatgoris": "womensfashion",
    "productSubCatgoris": "Kamiz",
    "productStoreName": "S-trade Store",
    "productId": "27",
    "productName": "Cotton Unstitched Salwar Kameez for Women - Pink",
    "productImage": "https://images.pexels.com/photos/15388429/pexels-photo-15388429.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "productPrice": "699",
    "productDiscount": "10",
    "offerStatus": false,
    "productBrand": "Strade",
    "ExpressDelivary": true,
    "FreeDelivary": true,
    "productStock": "60",
    "productSold": "10",
    "offerStartAndEnDate": "12-12-2021-01-04-2022",
    "offerName": "",
    "productDescription": ["Cotton Unstitched Salwar Kameez for Women - Pink"],
    "productSpecipication": {
      "Brand": "S-trade",
      "size": ["XL", "M", "L", "S", "2XL"],
      "gender": "Womens",
      "Color": ["Pink"]
    },
    "productShipping": "Dhaka city !!!! Feel free to buy from this site as we promise you same day delivery of any purchased items. Sookh helps you to purchase any goods or service with a very few steps. If you ever find any obligation of returning any purchased item or items, please review our Return & Refund Policy.",
    "productReviews": []
  },
  {
    "productCatgoris": "womensfashion",
    "productSubCatgoris": "Kamiz",
    "productStoreName": "S-trade Store",
    "productId": "28",
    "productName": "Cotton Unstitched Salwar Kameez for Women - Pink",
    "productImage": "https://images.pexels.com/photos/15388429/pexels-photo-15388429.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "productPrice": "699",
    "productDiscount": "10",
    "offerStatus": false,
    "productBrand": "Strade",
    "ExpressDelivary": false,
    "FreeDelivary": false,
    "productStock": "60",
    "productSold": "10",
    "offerStartAndEnDate": "12-12-2021-01-04-2022",
    "offerName": "",
    "productDescription": ["Cotton Unstitched Salwar Kameez for Women - Pink"],
    "productSpecipication": {
      "Brand": "S-trade",
      "size": ["41", "42", "43", "45"],
      "gender": "Womens",
      "Color": ["Pink"]
    },
    "productShipping": "Dhaka city !!!! Feel free to buy from this site as we promise you same day delivery of any purchased items. Sookh helps you to purchase any goods or service with a very few steps. If you ever find any obligation of returning any purchased item or items, please review our Return & Refund Policy.",
    "productReviews": []
  },
  {
    "productCatgoris": "womensfashion",
    "productSubCatgoris": "Kaftan",
    "productStoreName": "S-trade Store",
    "productId": "29",
    "productName": "Georgette Luxury Kaftan",
    "productImage": "https://images.pexels.com/photos/15388429/pexels-photo-15388429.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "productPrice": "699",
    "productDiscount": "10",
    "offerStatus": false,
    "productBrand": "Strade",
    "ExpressDelivary": true,
    "FreeDelivary": true,
    "productStock": "60",
    "productSold": "10",
    "offerStartAndEnDate": "12-12-2021-01-04-2022",
    "offerName": "",
    "productDescription": ["Georgette Luxury Kaftan"],
    "productSpecipication": {
      "Brand": "S-trade",
      "size": ["41", "42", "43", "45"],
      "gender": "Womens",
      "Color": ["Pink"]
    },
    "productShipping": "Dhaka city !!!! Feel free to buy from this site as we promise you same day delivery of any purchased items. Sookh helps you to purchase any goods or service with a very few steps. If you ever find any obligation of returning any purchased item or items, please review our Return & Refund Policy.",
    "productReviews": []
  },
  {
    "productCatgoris": "womensfashion",
    "productSubCatgoris": "Kaftan",
    "productStoreName": "S-trade Store",
    "productId": "30",
    "productName": "Georgette Luxury Kaftan",
    "productImage": "https://images.pexels.com/photos/15388429/pexels-photo-15388429.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "productPrice": "699",
    "productDiscount": "10",
    "offerStatus": false,
    "productBrand": "Strade",
    "ExpressDelivary": false,
    "FreeDelivary": false,
    "productStock": "60",
    "productSold": "10",
    "offerStartAndEnDate": "12-12-2021-01-04-2022",
    "offerName": "",
    "productDescription": ["Georgette Luxury Kaftan"],
    "productSpecipication": {
      "Brand": "S-trade",
      "size": ["41", "42", "43", "45"],
      "gender": "Womens",
      "Color": ["Pink"]
    },
    "productShipping": "Dhaka city !!!! Feel free to buy from this site as we promise you same day delivery of any purchased items. Sookh helps you to purchase any goods or service with a very few steps. If you ever find any obligation of returning any purchased item or items, please review our Return & Refund Policy.",
    "productReviews": []
  },
  {
    "productCatgoris": "womensfashion",
    "productSubCatgoris": "Kamiz",
    "productStoreName": "S-trade Store",
    "productId": "31",
    "productName": "Cotton Unstitched Salwar Kameez for Women - Pink",
    "productImage": "https://images.pexels.com/photos/15388429/pexels-photo-15388429.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    "productPrice": "699",
    "productDiscount": "10",
    "offerStatus": false,
    "productBrand": "Strade",
    "ExpressDelivary": false,
    "FreeDelivary": false,
    "productStock": "60",
    "productSold": "10",
    "offerStartAndEnDate": "12-12-2021-01-04-2022",
    "offerName": "",
    "productDescription": ["Cotton Unstitched Salwar Kameez for Women - Pink"],
    "productSpecipication": {
      "Brand": "S-trade",
      "size": ["40", "41", "42", "43", "45"],
      "gender": "Womens",
      "Color": ["Pink"]
    },
    "productShipping": "Dhaka city !!!! Feel free to buy from this site as we promise you same day delivery of any purchased items. Sookh helps you to purchase any goods or service with a very few steps. If you ever find any obligation of returning any purchased item or items, please review our Return & Refund Policy.",
    "productReviews": []
  },
]

I have to find all products based on a given size array. That size needs to match the productSpecipication > Size[] array. if matched, it will return the particular products as a products array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment