Home > Enterprise >  Reduce object with array properties to a boolean that is true if any of the arrays is not empty
Reduce object with array properties to a boolean that is true if any of the arrays is not empty

Time:09-21

I have this object:

filters: {
  field1: [?],
  field2: [?],
  field3: [?],
  etc
}

The result I want is a boolean that states whether any of the filters arrays has something in ithem (i.e: is not empty).

Something lile:

const hasActiveFilters = Object.values(filters).reduce(...);

What would be the best way to achieve this?

CodePudding user response:

.some would be more appropriate, to test if any of the values in the values array fulfill a condition.

const hasActiveFilters = Object.values(filters).some(arr => arr.length);

CodePudding user response:

You can use Array.some to check if any of the filter field arrays is not empty:

const data = {
  filters: {
    field1: [],
    field2: [],
    field3: [],
  }
}

const hasActiveFilters = (filters) => Object.values(filters).some(a => a.length)

console.log(hasActiveFilters(data.filters))

data.filters.field2.push('xyz')

console.log(hasActiveFilters(data.filters))

CodePudding user response:

You can try .some

const filters1 = {
  field1: [],
  field2: [],
  field3: undefined
}
const filters2 = {
  field1: undefined,
  field2: undefined,
  field3: []
}
const filters3 = {
  field1: [1, 2, 3],
  field2: [1],
  field3: {}
}
const hasLength = x => x && x.length;
const hasActiveFilters1 = Object.values(filters1).some(hasLength);
const hasActiveFilters2 = Object.values(filters2).some(hasLength);
const hasActiveFilters3 = Object.values(filters3).some(hasLength);
console.log(hasActiveFilters1); // false
console.log(hasActiveFilters2); // false
console.log(hasActiveFilters3); // true

  • Related