慕田峪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) => { if(acc[o[0]]){ acc[o[0]] = Math.max(o[1], acc[o[0]]); }else{ acc[o[0]] = o[1]; } 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)); //If Set doesn't work use the array, but this will not be a constant time lookup//var lookup = [].concat.apply([], arr2); 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) => { if(acc[o[0]]){ acc[o[0]] = Math.max(o[1], acc[o[0]]); }else{ acc[o[0]] = o[1]; } return acc;},{}));console.log(data);