Flaviodc
Flaviodc

Reputation: 1

Basic Javascript, How can i filter an array by numeric value?

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).

Upvotes: 0

Views: 326

Answers (3)

Tirtha
Tirtha

Reputation: 872

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);

Upvotes: 0

Love Akinlesi
Love Akinlesi

Reputation: 1

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 ]

Upvotes: 0

nick zoum
nick zoum

Reputation: 7285

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);

Upvotes: 1

Related Questions