赞
踩
JS取出两个数组中的不同或相同元素_js两个数组取相同项_Sleeping_Fairy的博客-CSDN博客
- var arr1 = [0,1,2,3,4,5];
- var arr2 = [0,4,6,1,3,9];
- function getArrDifference(arr1, arr2) {
- return arr1.concat(arr2).filter(function(v, i, arr) {
- return arr.indexOf(v) === arr.lastIndexOf(v);
- });
- }
- console.log(getArrDifference(arr1,arr2));
-
- //输出:(4) [2, 5, 6, 9]
- for (let i = 0; i < arr2.length; i++) {
- for (let j = 0; j < arr1.length; j++) {
- if(arr1[j] === arr2[i]){
- newArr.push(arr1[j]);
- }
- }
- }
- //先循环少的数组
- datas.forEach((element) => {
- const arr = vm.userList.filter((item) => {
- return item.accountId === element.userId
- })
- const obj = {}
- obj.loginName = arr[0].loginName || ''
- const add = Object.assign(element, obj)
- vm.fieldsList.push(add)
- })
-
- var arr1 = [0,1,2,3,4,5];
- var arr2 = [0,4,6,1,3,9]; //输出:(4) [0, 4, 1, 3]
- //两种数组长度都可以↑,注意循环顺序
- var arr1 = [0,1,2,3,4,5];
- var arr2 = [0,4,6,1];//输出:(4) [0, 4, 1]
- //先循环少的数组
- function getArrEqual(arr1, arr2) {
- let newArr = [];
- for (let i = 0; i < arr2.length; i++) {
- for (let j = 0; j < arr1.length; j++) {
- if(arr1[j] === arr2[i]){
- newArr.push(arr1[j]);
- }
- }
- }
- return newArr;
- }
- console.log(getArrEqual(arr1, arr2));
- //输出:(4) [0, 4, 1]
- var arr1 = [0,1,2,3,4,5];
- var arr2 = [0,4,6,1,3,9];
- //定义一个函数
- function exist(num, arr1) {
- for (var j = 0; j < arr1.length; j++) {
- if (num === arr1[j]) {
- return false; //如果传过来的元素在arr1中能找到相匹配的元素,我们返回fasle
- }
- }
- return true; //如果不能找到相匹配的元素,返回true
- }
- //这里我们将长度较长的数组放入函数中进行比较,看哪几个数不在较短的函数中,再将它们放入新的数组中
- var newArr = [];
- for (var i = 0; i < arr2.length; i++) {
- //我们将arr2中的元素依次放入函数中进行比较,然后接收函数的返回值
- if (exist(arr2[i], arr1)) { //如果返回的值是true,我们将元素放入新的数组中
- newArr[newArr.length] = arr2[i];
- }
- }
- console.log(newArr);
- //输出:(2) [6, 9]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。