JS处理两个数组,数组A有a,b,c,d四个值数组B有a,c两个值,处理后新的数组为b,d值

JavaScript09

JS处理两个数组,数组A有a,b,c,d四个值数组B有a,c两个值,处理后新的数组为b,d值,第1张

以int类型数组对比为例

import java.util.ArrayList

import java.util.List

public class ABC {

public static void main(String[] args) {

int[] aryA = { 1, 3, 5, 7, 9, 11, 13 }//要比较的数组啊A

int[] aryB = { 2, 4, 6, 8, 10, 5, 7, 9 }//要比较的数组啊B

List<Integer>list = new ArrayList<Integer>()//不知道有多少不同元素,因此用List

for (int i = 0i <aryB.lengthi++) {

boolean isExistInAryA = false

for (int j = 0j <aryA.lengthj++) {

if (aryA[j] == aryB[i]) {

isExistInAryA = true

break

}

}

if (!isExistInAryA) {

list.add(aryB[i])

}

}

int[] aryC = new int[list.size()]//存放不同元素的数组C

for (int i = 0i <list.size()i++) {

aryC[i] = list.get(i).intValue()

}

System.out.println("Different elment in array A and B are: ")

for (int value : aryC) {//打印输出数组中的不同元素

System.out.print(value + " ")

}

}

}

-----------------

Different elment in array A and B are:

2 4 6 8 10

var c = a.concat(b),//合并成一个数组

temp = {},//用于id判断重复

result = []//最后的新数组

//遍历c数组,将每个item.id在temp中是否存在值做判断,如不存在则对应的item赋值给新数组,并将temp中item.id对应的key赋值,下次对相同值做判断时便不会走此分支,达到判断重复值的目的;

c.map((item,index)=>{

if(!temp[item.id]){

result.push(item)

temp[item.id] = true

}

})

console.log(result)