Home > Blockchain >  Setting variable to first defined array
Setting variable to first defined array

Time:02-05

I have a variable called definedArray that I'd like to set to the first array in conditional that is not empty. Is there a simpler/cleaner away to achieve this?

Current Code

const definedArray = this.state.priceRange.length ? this.state.priceRange : filterParams.length ? filterParams : defaultPriceRange

I originally thought this may work but found the || operator set my variable with empty array:

const definedArray = this.state.priceRange || filterParams || defaultPriceRange

CodePudding user response:

You could get clever with the && and || operators, but honestly I don't know if it'd be that much more readable than using ternaries.

(this.state.priceRange.length && this.stage.priceRange) || (filterParams.length && filterParams) || ...

let arr1 = [];
let arr2 = [1,2,3];
let arr3 = [4,5,6];

let arr4 = (arr1.length && arr1) || (arr2.length && arr2) || (arr3.length && arr3);

console.log(arr4); // should be [1,2,3] as first non-empty
arr2 = [];
arr4 = (arr1.length && arr1) || (arr2.length && arr2) || (arr3.length && arr3);
console.log(arr4); // should be [4,5,6] as first non-empty

CodePudding user response:

Util method with reduce will be handy and will work with more than 3 arrays as well.

const define = (...items) =>
  items.reduce((acc, curr) => 
     (acc.length > 0 ? acc : curr)
  );

console.log("a", define([], [], [1]));

console.log("b", define([], [2], [1]));

console.log("c", define([3], [2], [1]));

// For your example
const definedArray = define(
  this.state.priceRange,
  filterParams,
  defaultPriceRange
);

  •  Tags:  
  • Related