0
["Ahmed", 8],
  ["Clement", 10],
  ["Elamin", 6],
  ["Adam", 7],
  ["Tayoa", 11],
  ["Nina", 10],
  ["Bob", 9],
  ["Lee", 1]

In the above array, how can I retrieve names value whose second key value is greater than 8? any help appriciated.Thank you

2
  • that is not a single array those are individual arrays can you tell what is wrapping them? are they an array of array or an objects of arrays? Commented May 5, 2020 at 0:04
  • Hi @HadiPawar it is an array of array .Thank you. Commented May 5, 2020 at 0:09

2 Answers 2

2

This approach requires iterating over the array twice by first filtering out the invalid elements and then mapping over the array to pluck out the name.

Note that this is leveraging array destructuring which allows us to nicely give the value at a given index a name, rather than trying to remember the index offset and what it means.

const data = [
  ["Ahmed", 8],
  ["Clement", 10],
  ["Elamin", 6],
  ["Adam", 7],
  ["Tayoa", 11],
  ["Nina", 10],
  ["Bob", 9],
  ["Lee", 1]
]

const filtered = data.filter(([_name, num]) => num > 8).map(([name]) => name)

console.log(filtered)

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

Comments

1

You can reduce() the array in one pass by checking if the second element in the array (age?) is more than 8, if so, add the first element in the array (the name) to the accumulator array, like so:

let arr = [
  ["Ahmed", 8],
  ["Clement", 10],
  ["Elamin", 6],
  ["Adam", 7],
  ["Tayoa", 11],
  ["Nina", 10],
  ["Bob", 9],
  ["Lee", 1],
];

let result = arr.reduce((acc, [name, age]) => (age > 8 && acc.push(name), acc), []);

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.