1
const array1 = [
   {currency: 'CNY', value: 1 },
   {currency: 'USD', value: 2 }
]

const array2 = [
   {currency: 'CNY', value: 332 },
   {currency: 'USD', value: 424 },
   {currency: 'HK', value: 123 }
]

数组array1array2,现在需要根据array1子元素的currency字段,删除array2中多余的子元素,
即得到

const array2 = [
   {currency: 'CNY', value: 332 },
   {currency: 'USD', value: 424 }
]

怎么写啊,,想了好久都没实现~~~!!!!

Demo_Hu 462
2019-07-12 提问
8 个回答
5

已采纳
let result = array2.filter(item => array1.some(value => value.currency == item.currency))
2
const currency = array1.map(item => item.currency)
array2.filter(item => currency.includes(item.currency))
1
var array1 = [
   {currency: 'CNY', value: 1 },
   {currency: 'USD', value: 2 }
]
var array2 = [
   {currency: 'CNY', value: 332 },
   {currency: 'USD', value: 424 },
   {currency: 'HK', value: 123 }
]

function arrFormat(arr1,arr2){
    let newarr=[];
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
           if(arr2[j].currency==arr1[i].currency){
                newarr.push(arr1[i]);
        }
        }
        
    }
    return newarr;
}
array2 = arrFormat(array1,array2);
console.log(array2);
0
let array1 = [
   {currency: 'CNY', value: 1 },
   {currency: 'USD', value: 2 }
]

let array2 = [
   {currency: 'CNY', value: 332 },
   {currency: 'USD', value: 424 },
   {currency: 'HK', value: 123 }
]
function uniqueByProperty(arr, prop) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i][prop] === arr[j][prop]) {
                arr.splice(j, 1);
                j--;
            }
        }
    }
    return arr;
}
  array1.map((a1) => {
     uniqueByProperty(array2, a1.currency)
  })
0

1、遍历array1,
2、然后去array2中进行元素查找,没有找到,就删除数组中该下标的值
涉及的代码有:数组循环,array.prototype.filter, array.prototype.some这两个方法可实现数组查找,splice

0
const intersection = (arr1, arr2, id) => {
    let arr = [];
    for(let item of arr1){
        if(arr2.find(v => v[id] === item[id])) {
            arr.push(item);
        }
    }
    return arr;
}
intersection(arr1,arr2,currency)
0
function filterArray (arr1, arr2) {
    let arr = []
    arr1.forEach((item, index) => {
           arr2.forEach((item2,index) => {
              if(item.currency === item2.currency) {
                 arr.push(item)
              }
           })      
    })
    return arr
}
filterArray(array1, array2)
0
for (var i = 0; i < array2.length; i++) {
    let ar = array2[i]
    if(!(array1.some(item=>{
       return item.currency == ar.currency
    }))){
      array2.splice(i,1)
    }
  }
}

撰写答案

推广链接