比较两个尺寸和返回第一个数组中元素的序列号的数组,它们与第二个数组中的元素相似
示例:
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]
您可以使用 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; }