简体   繁体   中英

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

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

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

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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM