当另一个数组有一个 Number(value) 时,如何匹配 2 个数组的字符串值

我是 Javascript 的新手。我正在尝试获取数组(arr1)的 Math.max(...arr1[i][1]),仅当它与第二个数组(arr2)匹配时。然后,将它推到数组(arr3)上,结果应该没有重复的值。


我尝试迭代两个数组(arr1 和 arr2),然后使用“if 语句”来匹配它们。


var arr1 = [ [ 'abandon', -2 ],

[ 'abandon', 1 ],

[ 'abandon', -2 ],

[ 'abduct', 1 ],

[ 'abduct', -2 ],

[ 'abduct', -2 ],

[ 'abhor', -3 ],

[ 'abhor', 1 ],

[ 'abhor', -1 ],

[ 'abil', 2 ],

[ 'abil', 4 ] ];



var arr2 = [ [ 'abandon' ],

[ 'abil' ],

[ 'abhor' ],

[ 'abduct' ],

['test'],

['hey'],

['testAgain'],

['array']];


var arr3 = [];


const mapping = arr2.map(word => {

    return word

})


for(var i = 0; i < arr1.length; i++){


    if(arr1[i][0] === mapping){

        arr3.push(Math.max(...arr1[i][1]))

    }


}

let arr4 = [...new Set(arr3)]


//example result:


var arr4 = [[abandon, -2],

[abduct, -2],

[abhor, -3],

[abil, 4]... and so on]

我知道我做错了什么,我别无选择。需要帮忙。


慕虎7371278
浏览 153回答 2
2回答

慕田峪7331174

您可以更好地使用 aSet而不是arr2直接使用数组来查找匹配项,因为在 a 的情况下它将是恒定时间查找Set。然后使用 aArray.prototype.filter过滤数组arr1并获取arr2.最后Array.prototype.reduce将帮助您创建一个对象,其键是单词,值是该单词中该单词的最大值arr1,您可以使用Object.entries从该对象返回reduce的 2-D 数组形式获取数据:var arr1 = [ [ 'abandon', -2 ],[ 'abandon', 1 ],[ 'abandon', -2 ],[ 'abduct', 1 ],[ 'abduct', -2 ],[ 'abduct', -2 ],[ 'abhor', -3 ],[ 'abhor', 1 ],[ 'abhor', -1 ],[ 'abil', 2 ],[ 'abil', 4 ] ];var arr2 = [ [ 'abandon' ],[ 'abil' ],[ 'abhor' ],[ 'abduct' ],['test'],['hey'],['testAgain'],['array']];var lookup = new Set(arr2.flat());var mapping = arr1.filter(([word, val]) => lookup.has(word));var data = Object.entries(mapping.reduce((acc, o, i) => {&nbsp; &nbsp; if(acc[o[0]]){&nbsp; &nbsp; &nbsp; &nbsp; acc[o[0]] = Math.max(o[1], acc[o[0]]);&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; acc[o[0]] = o[1];&nbsp; &nbsp; }&nbsp; &nbsp; return acc;},{}));console.log(data);编辑形成你的意见我假设你正在使用节点运行的旧版本在那里flat()是不存在的Array.prototype。所以你可以使用下面编辑过的片段:var arr1 = [ [ 'abandon', -2 ],[ 'abandon', 1 ],[ 'abandon', -2 ],[ 'abduct', 1 ],[ 'abduct', -2 ],[ 'abduct', -2 ],[ 'abhor', -3 ],[ 'abhor', 1 ],[ 'abhor', -1 ],[ 'abil', 2 ],[ 'abil', 4 ] ];var arr2 = [ [ 'abandon' ],[ 'abil' ],[ 'abhor' ],[ 'abduct' ],['test'],['hey'],['testAgain'],['array']];//flatten using Array.prototype.concatvar lookup = new Set([].concat.apply([], arr2));&nbsp;//If Set doesn't work use the array, but this will not be a constant time lookup//var lookup = [].concat.apply([], arr2);&nbsp;&nbsp;var mapping = arr1.filter(([word, val]) => lookup.has(word));//If you are not using Set and going with an array, use Array.prototype.includes, so search won't be O(1)//var mapping = arr1.filter(([word, val]) => lookup.includes(word));var data = Object.entries(mapping.reduce((acc, o, i) => {&nbsp; &nbsp; if(acc[o[0]]){&nbsp; &nbsp; &nbsp; &nbsp; acc[o[0]] = Math.max(o[1], acc[o[0]]);&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; acc[o[0]] = o[1];&nbsp; &nbsp; }&nbsp; &nbsp; return acc;},{}));console.log(data);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript