Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does js get the same and different values in two arrays and array objects

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

本篇内容主要讲解"js怎么获取两个数组及数组对象中相同和不相同的值",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"js怎么获取两个数组及数组对象中相同和不相同的值"吧!

1、获取两个数组中相同的元素

var arr1 = [0,1,2,3,4,5];var arr2 = [0,4,6,1,3,9];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));//[0, 4, 1, 3]

2、获取两个数组中不相同的元素

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)); // [2, 5, 6, 9]

3、获取两个数组对象中相同的值

function getArrDifSameValue(arr1,arr2){ var result = []; for(var i = 0; i < arr2.length; i++){ var obj = arr2[i]; var id = obj.id; var isExist = false; for(var j = 0; j < arr1.length; j++){ var aj = arr1[j]; var n = aj.id; if(n == id){ isExist = true; break; } } if(isExist){ result.push(obj); } } return result;} var arr1 = [ {"id": "A"},{"id": "B"}];var arr2 = [ {"id": "A"}, {"id": "B"},{"id": "C"}];console.log(getArrDifSameValue(arr1,arr2));

4、获取两个数组对象中不相同的值

function getArrDifSameValue(arr1,arr2){ var result = []; for(var i = 0; i < arr2.length; i++){ var obj = arr2[i]; var id = obj.id; var isExist = false; for(var j = 0; j < arr1.length; j++){ var aj = arr1[j]; var n = aj.id; if(n == id){ isExist = true; break; } } if(!isExist){ result.push(obj); } } return result;} var arr1 = [ {"id": "A"},{"id": "B"}];var arr2 = [ {"id": "A"}, {"id": "B"},{"id": "C"}];console.log(getArrDifSameValue(arr1,arr2));// [{"id": "C"}]到此,相信大家对"js怎么获取两个数组及数组对象中相同和不相同的值"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report