[英]Javascript : Compare two arrays and fill non matching elements with existing elements
我有一個數組1
var arr1 = ["27", "20", "18", "15", "14", "13", "8", "6", "2", "1"]
我有另一個數組 2,它總是顯示從 1 到 30
var arr2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]
我想比較這兩個 arrays 並在數組 1 中為數組 1 中不存在的值的 rest 填充“NULL”
基本上我的最終數組應該顯示為
finalArray = ["1", "2", null, null, null, "6", null, "8", null, null, null, null, "13", "14", "15", null, null, "18", null, null, null, null, null, null, null, null, "27", null, null, null]
嘗試在第二個數組中循環第一個數組。 但是未能將 null 值推送到元素的 rest。 如何做到這一點? TIA
您可以通過遍歷 arr2 並檢查當前項目是否在 arr1 中簡單地執行以下操作。 如果項目在 arr1 中,則將項目放入新數組中,否則放入 null,
var arr1 = ["27", "20", "18", "15", "14", "13", "8", "6", "2", "1"] var arr2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"] res = arr2.map(item => arr1.includes(item)? item: null); console.log(res);
我會以不同的方式來做。
首先,使用arr1
創建一個Map
然后循環通過主數組,即arr2
並檢查該值是否存在於Map
中。 如果可用,請使用相同的內容,否則使用 null 填充。
var arr1 = ["27", "20", "18", "15", "14", "13", "8", "6", "2", "1"] var arr2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]; //Create a MAP using `arr1` so that while searching it'll be easy let mappingObj = {}; arr1.forEach(val => { mappingObj[val] = val; }); let res = arr2.map(val => mappingObj[val] || null) console.log(res);
如果arr2
總是包含從'1'
到'30'
排序的數字字符串,你甚至不需要使用它。 您可以執行以下操作:
const arr1 = ["27", "20", "18", "15", "14", "13", "8", "6", "2", "1"]; const finalArray = (new Array(30)).fill(null); arr1.forEach(item => { finalArray[parseInt(item) - 1] = item; }); console.log(finalArray);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.