DEV Community

loading...

How to conditionally select array or array of objects in Javascript ?

jav7zaid
Yearning for Javascript
Updated on ・1 min read

If you have ever come across a use case where you have multiple arrays like below,

const array1 = [1,2,3];
const array2 = [4,5,6];
const array3 = [{ a: 1 }, { b: 2 }];

Enter fullscreen mode Exit fullscreen mode

What if you want the resultant array to conditionally include one or more arrays, one way to do it

const arrayWeWant = [];

if(condition1) {
 arrayWeWant.push(array1);
}

if(condition2) {
 arrayWeWant.push(array2);
}

if(condition3) {
 arrayWeWant.push(array3);
}
Enter fullscreen mode Exit fullscreen mode

well that's not a bad approach, but we can do better

const arrayWeWant = [
  ...(condtion1 ? array1 : []),
  ...(conditon2 ? array2 : []),
  ...(conditon3 ? array3 : [])
];

Enter fullscreen mode Exit fullscreen mode

It's a much cleaner way isn't it.

Happy to share!😊

Discussion (2)

Collapse
raulcg profile image
RaulC-G

//hashmap of arrays
var arrayStore = {
array1: [1,2,3],
array2: ["a", "b", "c"],
array3: [{id: 1}, {id: 2}]
};

// you access to arrays with a name as string.
// if name doesn't exixts in the hashmap, assing
// an empty array as default value.
var array = arrayStore[nameOfArray] || [];

Collapse
arnabxd profile image
Arnab Paryali

I used this many times before and I like it this way