# 如何比较两个数组，然后确定元素的位置？

[B, C]

[A, B, C, D, E]

### 回答：

``````var a=['B', 'C'],
b=['A', 'B', 'C', 'D', 'E'];
var r=a.map(function(item){
return b.indexOf(item);
});
console.log(r);``````

### 回答：

``````arr1 = [B, C];
arr2 = [A, B, C, D, E];
indexs = [arr1.length]
for (i = 0; i < arr1.len; i++) {
for (j = 0; j < arr2.len; j++) {
if (arr1[i] != arr2[j]) continue;
indexs[i] = j;
break;
}
}``````

### 回答：

``````const arrA = ['B', 'C']
const arrB = ['A', 'B', 'C', 'D', 'E']
let indexArr = []

arrA.forEach(item => {
indexArr.push(arrB.indexOf(item))
})``````

indexArr 就是元素所在位置的数组，值为 -1 代表数组 B 中未找到相同元素

### 回答：

ES6:

``````        const ah = ['a', 'b'];
const bh = [1, 3, 'a', '6', 'b', 8];
const h = (arga, argb) => arga.map(v => {
return { val: v, index: argb.findIndex(val => val === v) }
})

console.log(h(ah, bh))``````

### 回答：

js:

``````    const a = ['b', 'c'];
const b = ['a', 'b', 'c', 'd', 'e'];
let index_result = [];
a.forEach(item => {
index_result.push(b.indexOf(item));
});
console.log(index_result);``````

### 回答：

function (arr1,arr2){

``````let keyIndexPair = [];
arr2.forEach(item2=>{
arr1.forEach(item1=>{
if(item1 === item2){
let result = {};
result.key = item1;
result.index = arr2.indexOf(item2);
keyIndexPair .push(result);
}
});
});
return keyIndexPair;``````

}