![](/img/trans.png)
[英]How can I get a javascript function in snowflake to return one value if the argument is numeric or another value if the argument is not numeric?
[英]Basic Javascript, How can i filter an array by numeric value?
這是我在這個社區的第一個問題,我是一名 JavaScript 新手程序員。
我有這樣的事情:
let dog = [["extra small", 2], ["small", 5], ["medium", 7], ["big", 9], ["extra big", 12]];
取前一個數組的數據,我想用數值創建一個新數組,例如:
ages = [2, 5, 7, 9, 12]
我嘗試使用“過濾器”,但我不知道如何正確使用它,我也嘗試搜索一些參考資料以使其工作,但我不能。
提前致謝(也很抱歉我的英語不好,但我想你明白了)。
您可以先使用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);
以下是我對如何實現這一目標的想法。
使用Array#Map和Array#filter 。 基本上,映射數組的每個元素,然后使用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 ]
- 使用功能。 這與第一個類似,但是,我們使用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.