0

this is my first question on this community and i'm a novice programmer with JavaScript.

I have something like this:

let dog = [["extra small", 2], ["small", 5], ["medium", 7], ["big", 9], ["extra big", 12]];

Taking the data of the previous array, i want to create a new array just with the numeric values, for example:

ages = [2, 5, 7, 9, 12]

I tried to use "filter", but i don't know how to properly use it, also i tried to search some references to make it work but i couldn't.

Thanks in advance (and sorry for my poor english, but i suppose you get the idea).

3 Answers 3

1

You can first use Array#map to get just the numbers and then Array#sort to sort the numbers

let dog = [
  ["extra small", 2],
  ["small", 5],
  ["medium", 7],
  ["big", 9],
  ["extra big", 12]
];

let ages = dog.map(([size, age]) => age).sort((a, b) => a - b);

console.log(ages);

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

Comments

0

Here are my thoughts on how to achieve this.

  1. Using Array#Map and Array#filter. Basically, mapping each element of the array, then checking for the numeric values in the subArray using JavaScript#isNaN() and returning the numbers.

    • isNaN() checks if the value type is not a number. !isNaN() reverses that response.
    • flat() is used to flatten the final result to a single array. Alternatively, you can change map() to flatMap()
 // map(), isNaN(), filter(), flat()
 let newArr = dog.map((arr) => arr.filter((val) => !isNaN(val))).flat();
 console.log(newArr); // [ 2, 5, 7, 9, 12 ]


 // flatMap(), isNaN(), filter()
 let newArr = dog.flatMap((arr) => arr.filter((val) => !isNaN(val)));
 console.log(newArr); // [ 2, 5, 7, 9, 12 ]
  1. Using function. This is similar to the first, however, instead of using map() we use a Array#forEach to loop through the array.
function getNumeric(array) {
    let result = [];
    array.forEach((arr) => {
        let res = arr.filter((a) => !isNaN(a));
        result.push(...(res));
    });
    return result;
}
let newArr = getNumeric(dog);
console.log(newArr); // [ 2, 5, 7, 9, 12 ]

Comments

0

let dog = [
  ["extra small", 2],
  ["small", 5],
  ["medium", 7],
  ["big", 9],
  ["extra big", 12]
];

const newArr = dog.map(item => {
  return item[1]
})

console.log(newArr);

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.