比较具有不同大小的两个数组并返回第一个数组中元素序列号的数组,这与第二个数组中的元素类似
示例:
arr1 [1,2,3,4,5,8,11,16,19]
arr2 [90,54,34,12,1,2,3,4,5,7,82]
必须返回:
arr3 [0,1,2,3,4]
答案 0 :(得分:1)
您可以使用Array#reduce
并检查元素是否在第一个数组中,然后返回位置。
function getCommon(a1, a2) {
return a2.reduce(function (r, a) {
var p = a1.indexOf(a);
return p !== -1 ? r.concat(p) : r;
}, []);
}
console.log(getCommon([1, 2, 3, 4, 5, 8, 11, 16, 19], [90, 54, 34, 12, 1, 2, 3, 4, 5, 7, 82]));
console.log(getCommon([1, 2, 3, 4, 5, 6, 7], [23, 45, 67, 76, 2, 4, 6]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6
const getCommon = (a, b) => b.reduce((r, c) => r.concat(a.indexOf(c) + 1 ? a.indexOf(c) : []), []);
console.log(getCommon([1, 2, 3, 4, 5, 8, 11, 16, 19], [90, 54, 34, 12, 1, 2, 3, 4, 5, 7, 82]));
console.log(getCommon([1, 2, 3, 4, 5, 6, 7], [23, 45, 67, 76, 2, 4, 6]));
.as-console-wrapper { max-height: 100% !important; top: 0; }