Home > Blockchain >  a function for data filtration based on two arrays of strings in Javascript
a function for data filtration based on two arrays of strings in Javascript

Time:04-15

I need some help with array filtration. I want to filter an array of objects based on:

Note: these arrays can be empty. When they are empty, the function should return the original array (without data filtration)

brands: ["brand 1", "brand 2", "brand 3", "brand 4"],
tags: ["tag1", "tag2", "tag 3", "tag 4"],

The array of objects which I want to do filter looks like this:

[
 {
    "tags": [
      "tag1"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand 1",
  },
 {
    "tags": [
      "tag1", "tag2"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand 1",
  },
 {
    "tags": [
      "tag1", "tag3", "tag4"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand 4",
  },
 {
    "tags": [
      "tag1", "tag2"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand1 ",
  },
]

the function I have looks like this doing filtration on the manufacturer only:

const obj = {
  brands: ["brand 1", "brand 2"],
  tags: ["tag1", "tag2", "tag 4"],
}

const filterArray = (obj, array) => {
  let newArray = []
  const byBrands = array.filter((item) =>
    obj.brands.includes(item["manufacturer"].toLowerCase())
  )

  if (byBrands.length > 0) {
    newArray = byBrands
  } else {
    newArray = array
  }

  return newArray;
}

I need a function to do filtration on tags and manufacturer at the same time.

Thanks, Stakoverflow :)

CodePudding user response:

You should use keys in your filter object that match properties in the objects to be filtered, otherwise there's no way to know which property compare. Other than that it's just a matter of checking if every() property in the filter object has some() matching entry in the object being filtered. The example ignores empty arrays in the filter object using an OR (||) short-circuit, and uses concat() to evaluate every property as an array.

(You can fine tune to make it case-insensitive, search for substrings, etc.)

const input = [{ "tags": ["tag1"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 1", }, { "tags": ["tag1", "tag2"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 1", }, { "tags": ["tag 4"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 2", }, { "tags": ["tag 3"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 1", },]

const obj = {
  manufacturer: ["brand 1", "brand 2"],
  tags: ["tag1", "tag2", "tag 4"],
  name: [], // ignores empty arrays
}

function filterProducts(array, filters) {
  return array.filter(p =>
    Object.entries(filters).every(([k, fs]) =>
      !fs.length || fs.some(f => [].concat(p[k]).some(t => t === f)))
  )
}

console.log(filterProducts(input, obj))

  • Related