Is there a way I can skip checking array length every time I want to use a filter, map, or any other method used on arrays?
const newArray = array.length ? array.filter(n=>n.id=id) : [];
const otherArray = array.length ? array.map(n=>n.id=id) : [];
You don't have to check them.
const testArr = [];
const anotherArr = testArr.map((item) => {
// do something with item;
return transformedItem;
});
// anotherArr is [];
const anotherArr2 = testArr.filter((item) => {
// do something with item;
return boolean;
});
// anotherArr2 is still [];
You don’t need to check the length, if array length is 0 then after the map or filter operation would give you empty array.
Here the assumption is, the array variable is an empty array but not undefined.
The callback is invoked for each element of the array. If there is no element, it won't be invoked.
Just don't check it :
const array = [];
const id = 42;
const newArray = array.filter(n => n.id === id);
const otherArray = array.map(n => n.id = id);
console.log(newArray);
console.log(otherArray);
[].forEach(elem => console.log("Hello world ")); // no output
You don't need to do anything, just call a function .map() or .filter() etc..It returns empty array( []) if nothing return.
const array = [];
const mapped = array.map(() => {})
console.log(mapped);
You can try something similar to:
const newArray = array.length && array.filter(n=> n.id === id);
Or you can create a wrapper method and have a logic in that returns array on which you can further modify as per your logic.
function isArrayValid(array, callback) {
if (Array.isArray(array)) {
return callback(array);
}
return [];
}
const newArray = isArrayValid(array, (_validArray) => {
return _validArray.filter(n => n.id === id);
});
const otherArray = isArrayValid(array, (_validArray) => {
return _validArray.map(n => n.id * 2);
});
Hope it helps. Happy coding !
[]as a result if the length is 0..