1

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.

3 Answers 3

5

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah... That's kinda embarrassing. No idea why it didn't work for me when I tried - probably console logged the wrong value. Thank you anyway for the clarification!
3

Filter by the second element:

const array = [[ 'PENNY', 0 ],[ 'NICKEL', 0 ],[ 'DIME', 20 ],[ 'QUARTER', 50 ]];

const filtered = array.filter(([, count]) => count > 0);

console.log(filtered);

[, count] is destructuring, which you can read about in full here

1 Comment

Nice tip, i didn't know :)
0
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.

1 Comment

Same as the top voted answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.