2017-11-25 18 views
0

配列から文字列を削除する必要があります。この関数があります。 これはいくつかのランダムなテストを行い、結果を返します。配列からランダムな文字列を削除する、JavaScript

"Expected: '[1, 2]', instead got: '[1, 2, \'a\', \'b\']' 
Expected: '[1, 0, 15]', instead got: '[1, \'a\', \'b\', 0, 15]' 
Expected: '[1, 2, 123]', instead got: '[1, 2, \'aasf\', \'1\', \'123\', 
123]' 
Expected: '[]', instead got: '[\'a\', \'b\', \'1\']' 
Expected: '[1, 2]', instead got: '[1, 2, \'a\', \'b\']' " 
+0

を行います方法です。あなたの数値がすべて整数であれば、 'array.filter(Number.isInteger)'を使ってください。 –

答えて

0

かなり簡単です。ここでは、あなたの数字が+/-無限大が含まれていない場合、あなたは `array.filter(Number.isFiniteを)`使用することができ、それを

let data = [ 
 
    "Cat", 
 
    1451, 
 
    14.52, 
 
    true, 
 
    "I will be removed too :(" 
 
]; 
 

 

 
let filteredData = data.filter(item => typeof item !== "string"); 
 

 
console.log(filteredData); // or return it

+0

ありがとうございます! –

2

あなたが二回array filterを悪用している:私は(明らかに)未定義の取得は何も返しませんが、私はこれを取得配列を返すとき

function filter_list(array) { 
array.filter((elem) => typeof elem === "string"); 
return (array); 
} 

最初の問題は、フィルタを呼び出すと配列が変更されないことです。

// This code isn't the correct yet, continue below 
function filter_list(array) { 
    // You have to return the result of filter. The 'array' is not changed. 
    return array.filter((elem) => typeof elem === "string"); 
} 

第2の問題は、フィルタリングしたい反対のものをフィルタリングしていることです。

// Correct code 
function filter_list(array) { 
    // If the condition is true, the element will be kept in the NEW array. 
    // So it must be false for strings 
    return array.filter((elem) => typeof elem !== "string"); 
} 

filter() の各要素アレイに対して一度設けcallback関数を呼び出し、そして callbacktrueに強制変換値を返すためのすべての値の新しい配列を構築します。 callbackは、割り当てられた値を持つ配列のインデックスに対してのみ が呼び出されます。削除されたか、または 割り当てられた値に決して達していないインデックスに対しては、 は呼び出されません。 callbackテスト を通過しない配列要素は単にスキップされ、新しい配列には含まれません。

+0

私は見る!ご助力ありがとうございます!! –

関連する問題