0

I have the following:

const entries = 
[
   ["mango", 2],
   ["orange", 3],
   ["strawberry", 0],
   ["banana", 10]
]

I would like to iterate over the arrays inside entries[], remove any arrays that have a 0 and have them going in descending order, so the above would change to:

newArr = 
[
   ["banana", 10]
   ["orange", 3]
   ["mango", 2]
]

Thanks.

1
  • 4
    Take a look at filter and sort Commented Apr 15, 2020 at 15:37

4 Answers 4

1
let entries = 
[
   ["mango", 2],
   ["orange", 3],
   ["strawberry", 0],
   ["banana", 10]
]

entries = entries.filter(pr => pr[1] !== 0);
entries.sort((pr, nt) => nt[1] - pr[1])
Sign up to request clarification or add additional context in comments.

Comments

1

It can be done through filter and sort:

const result = entries.filter(f => f[1] != 0).sort((a, b)=> b[1] - a[1]);

An example:

let entries =
[
   ["mango", 2],
   ["orange", 3],
   ["strawberry", 0],
   ["banana", 10]
];


const result = entries.filter(f => f[1] != 0).sort((a, b)=> b[1] - a[1]);
console.log(result)

Comments

1

Using filter and sort:

const entries = [["mango", 2], ["orange", 3], ["strawberry", 0], ["banana", 10]]

function filterSort (arr) {
  return entries
    .filter(([, num]) => num > 0)
    .sort(([, a], [, b]) => b - a)
}

console.log(filterSort(entries))

Note that the entries array is not modified. No items were removed.

Comments

0

Use filter and sort methods with destructure.

const entries = [
  ["mango", 2],
  ["orange", 3],
  ["strawberry", 0],
  ["banana", 10]
];

const result = entries.filter(([,x]) => x).sort(([,a], [,b]) => b - a);

console.log(result);

Comments

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.