簡體   English   中英

提取數組之間的匹配值並將其保存到JavaScript中的新數組中

[英]Extracting matching values between arrays and saving them into a new array in javascript

我是編程新手,正在嘗試完成以下練習:

聲明一個新變量以存儲從a2提取的所有a1。 遍歷所有a2的元素,並僅提取與a1中的值匹配的元素。

 var a1 = ["5", "10"]; var a2 = [ ["10", "2", "10", "E", "5", "5", "u", "0", "5", "10", ":", "5"], ["10", "10", "5", "9", "10", "}", "5", "l", "5", "5", "5", "˜"], ["x", ".", "d", "2", "|", "[", "z", "8", "s", "d", "2", "5"] ]; var a3 = []; for (var i = 0; i < a2.length; i++) { for (var j = 0; j < a2[i].length; j++) { if (a1[0] === a2[i][j] || a1[1] === a2[i][j]) { a3 = a2[i][j]; console.log(a3); } else { console.log("false") } } } console.log(a3) 

目前,我有此代碼。 當我在循環外檢查a3時,我沒有得到預期的結果。 如何獲取匹配值以進入此新數組(a3)?

您需要執行a3.push在數組中添加元素

 var a1 = ["5", "10"]; var a2 = [ ["10", "2", "10", "E", "5", "5", "u", "0", "5", "10", ":", "5"], ["10", "10", "5", "9", "10", "}", "5", "l", "5", "5", "5", "˜"], ["x", ".", "d", "2", "|", "[", "z", "8", "s", "d", "2", "5"] ]; var a3 = []; for (var i = 0; i < a2.length; i++) { for (var j = 0; j < a2[i].length; j++) { if (a1[0] === a2[i][j] || a1[1] === a2[i][j]) { a3.push(a2[i][j]); } else {} } } console.log(a3); 

或者,您可以使用indexOfforEach

 var a1 = ["5", "10"]; var a2 = [ ["10", "2", "10", "E", "5", "5", "u", "0", "5", "10", ":", "5"], ["10", "10", "5", "9", "10", "}", "5", "l", "5", "5", "5", "˜"], ["x", ".", "d", "2", "|", "[", "z", "8", "s", "d", "2", "5"] ]; var a3 = []; a1.forEach(function(item) { if (a1.indexOf(item) !== -1) { a3.push(item) } }) console.log(a3); 

問題是您沒有在a3添加元素,而只是通過以下方式覆蓋了找到的每個匹配項中的整個a3

a3 = a2[i][j];

相反, 入數組:

a3.push(a2[i][j]);

此外,您的代碼當前假設a1永遠不會包含兩個以上的元素,因為您已經對代碼進行了硬編碼以僅查看其第一個和第二個元素。 我們可以通過詢問a1 “包含”給定值來使它更加動態:

for (var i = 0; i < a2.length; i++) {
    for (var j = 0; j < a2[i].length; j++) {
        if (a1.includes(a2[i][j])) a3.push(a2[i][j]); //includes() returns a boolean

您直接將匹配值分配給a3,而應該將值推入a3數組中。

而不是這樣做

a3 = a2[i][j];

做這個

a3.push(a2[i][j])

您可以使用.concat() .filter().includes()

let a3 = [].concat(...a2).filter(v => a1.includes(v));

描述:

  • 使用.concat()和`spread語法創建一個包含所有子數組的所有元素的數組。
  • 使用.filter()過濾此數組,以僅選擇通過過濾器測試的那些元素。
  • 其他數組中元素的存在可以使用.includes()檢查。

演示:

 let a1 = ["5", "10"], a2 = [["10", "2", "10", "E", "5", "5", "u", "0", "5", "10", ":", "5"],["10", "10", "5", "9", "10", "}", "5", "l", "5", "5", "5", "˜"],["x", ".", "d", "2", "|", "[", "z", "8", "s", "d", "2", "5"]]; let a3 = [].concat(...a2).filter(v => a1.includes(v)); console.log(a3); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

文檔:

您正在將值插入數組。 那應該是PUSH方法。

如果您嘗試使用(a3 = a2 [i] [j]),它將替換您以前的值。 請使用推入方法進行插入。 添加了以下代碼。 a3.push(10)

push()方法將新項目添加到數組的末尾。

// First we flatten the array to get rid of nested arrays
const flattened = a2.reduce((acc, val) => acc.concat(val), []);
// Then we loop through the flattened array and check if the current value (x) exists inside the a1 array - if true -> push to a3
flattened.map(x => a1.includes(x) && a3.push(x))

您可以結合使用Array.prototype.reduce() ,Array.prototype.concat()] 3Array.prototype.filter()Array.prototype.includes()

碼:

 const a1 = ["5", "10"]; const a2 = [["10", "2", "10", "E", "5", "5", "u", "0", "5", "10", ":", "5"], ["10", "10", "5", "9", "10", "}", "5", "l", "5", "5", "5", "˜"], ["x", ".", "d", "2", "|", "[", "z", "8", "s", "d", "2", "5"]]; const a3 = a2 .reduce((a, c) => a.concat(c), []) .filter(item => a1.includes(item)); console.log(a3); 

您可以使用filter()reduce()includes()Spread syntax (* ES6)獲得所需的結果。

ES5

 var a1 = ["5", "10"]; a2 = [["10", "2", "10", "E", "5", "5", "u", "0", "5", "10", ":", "5"],["10", "10", "5", "9", "10", "}", "5", "l", "5", "5", "5", "˜"],["x", ".", "d", "2", "|", "[", "z", "8", "s", "d", "2", "5"]]; var mergerResult = a2.reduce(function(r, v){ return r.concat(v); }, []); mergerResult = mergerResult.filter(function(value){ return a1.includes(value) }); console.log(mergerResult,'lenght',mergerResult.length); 

ES6

 const a1 = ["5", "10"]; a2 = [["10", "2", "10", "E", "5", "5", "u", "0", "5", "10", ":", "5"],["10", "10", "5", "9", "10", "}", "5", "l", "5", "5", "5", "˜"],["x", ".", "d", "2", "|", "[", "z", "8", "s", "d", "2", "5"]]; let mergerResult = a2.reduce((r, v) => [...v, ...r], []); mergerResult = mergerResult.filter(value=>a1.includes(value)); console.log(mergerResult,'lenght',mergerResult.length); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM