Basic question but its something that I've never quite understood with these array methods.
Say I have an array such as:
[[ 'PENNY', 0 ],[ 'NICKEL', 0 ],[ 'DIME', 20 ],[ 'QUARTER', 50 ]]
and I wanted to use filter to return a new array in which only elements are returned whose first index is greater than 0.
So it would return an array like so:
[ [ 'DIME', 20 ],[ 'QUARTER', 50 ]].
How would I go about this using filter? Some clarification would be appreciated.
Just use filter as you mention in question for compare if value is > of 0 like:
const array = [[ 'PENNY', 0 ],[ 'NICKEL', 0 ],[ 'DIME', 20 ],[ 'QUARTER', 50 ]];
console.log(array.filter(el => el[1] > 0));
Reference:
const array = [[ 'PENNY', 0 ],[ 'NICKEL', 0 ],[ 'DIME', 20 ],[ 'QUARTER', 50 ]]
const arrayFiltered = array.filter((item) => item[1] > 0)
console.log(arrayFiltered)
filter() method return a new array based on the rule you specify inside. In this case, we want a new array with item[1] (the index of our array) to be > 0.