Quick tip:
Consider utilizing the filter
method over a loop in most cases, unless performance is crucial and the loop significantly outperforms Array's filter
method without adding complexity.
const xs = [ 1, 2, 3, 4, 5 ] // array of values
const ys = [ 1, 3 ] // indices to skip
// using `filter`
const zs = xs.filter((_, i) => !ys.includes(i))
console.log(zs)
//=> [ 1, 3, 5 ]
In-depth explanation:
Avoid using loops whenever possible as they can make your code less readable compared to utilizing higher-order functions like higher-order functions, such as Array.prototype.filter
. This function allows you to selectively retain elements based on specified conditions. The callback function used with filter
should return a boolean indicating whether or not to keep the current element. In JavaScript, the filter
function takes two parameters: the array element and the index. Since we only need the index, we can disregard the element value by starting the function with (_, ...)
.
Array.prototype.includes
is a useful tool for checking if an array contains a specific value (e.g., [0].includes(0) === true
and [0].includes(1) == false
).
By combining these concepts, we can iterate through the initial array, xs
, checking against our blacklist of indices, ys
, to filter out unwanted elements.
If we were to use a map
function instead of filter
, including our evaluation results:
xs.map((v, i) => [ v, !ys.includes(i) ])
//=> [ [ 1, true ], [ 2, false ], [ 3, true ], [ 4, false ], [ 5, true ] ]
We could visualize which values would be considered ‘true’. Ultimately, filter
retains the elements that evaluate to ‘true’, resulting in [ 1, 3, 5 ]
.