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 }];
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);
}
well that's not a bad approach, but we can do better
const arrayWeWant = [
...(condtion1 ? array1 : []),
...(conditon2 ? array2 : []),
...(conditon3 ? array3 : [])
];
It's a much cleaner way isn't it.
Happy to share!😊
Top comments (2)
//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] || [];
I used this many times before and I like it this way