[英]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.这是我在这个社区的第一个问题,我是一名 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您可以先使用Array#map获取数字,然后使用Array#sort对数字进行排序
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.以下是我对如何实现这一目标的想法。
Using Array#Map and Array#filter .使用Array#Map和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.基本上,映射数组的每个元素,然后使用JavaScript#isNaN()检查 subArray 中的数值并返回数字。
// 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 ]
- Using function.使用功能。 This is similar to the first, however, instead of using map() we use a Array#forEach to loop through the array.这与第一个类似,但是,我们使用Array#forEach来循环遍历数组,而不是使用 map()。
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 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.