您的位置:首页技术文章
文章详情页

javascript 如何对两个数组进行比较

【字号: 日期:2023-06-09 09:24:12浏览:29作者:猪猪

问题描述

数组a

[{key:1,name:’name1’},{key:2,name:’name2’},{key:3,name:’name3’},{key:4,name:’name4’},{key:5,name:’name5’}]

数组b是在数组a的一部分

[{key:1,name:’name1’},{key:2,name:’name2’}]

数组c是在数组b的基础上进行修改

[{key:1,name:’name11’},{key:22,name:’name22’}]

现在需要最后的结果为key:1被修改,key:2被删除,key:3,key:4,key:5无变化保留,key:22被添加

[{key:1,name:’name11’},{key:3,name:’name3’},{key:4,name:’name4’},{key:5,name:’name5’},{key:22,name:’name22’}]

请问一下如何才能实现这个逻辑

问题解答

回答1:

你是要比较还是合并?合并用 deepmerge 很方便

回答2:

//引入Lodash_.extend(_.difference(a, b), c)回答3:

var a = [{key:1,name:’name1’},{key:2,name:’name2’},{key:3,name:’name3’},{key:4,name:’name4’},{key:5,name:’name5’}];var b = [{key:1,name:’name1’},{key:2,name:’name2’}];var c = [{key:1,name:’name11’},{key:22,name:’name22’}];var d = [];d = $.extend(a,(b,c));console.log(d);

extend方法 跟git 的merge差不多我那样写应该会得到你最后想要的那种结果

回答4:

function compare(val1,val2){ if(val1 < val2){return 1; }else if(val1 > val2){return -1; }else{return 0; }}var values = [1,2,50,60,10,20,80];values.sort(compare);alert(values); //80,60,50,20,10,2,1回答5:

如果找不到好的工具,或者不想污染命名空间,那就把数组解耦,这样应该可以满足你的要求

let a = [{ key: 1, name: ’name1’ }, { key: 3, name: ’name3’ }, { key: 2, name: ’name2’ }, { key: 4, name: ’name4’ }, { key: 5, name: ’name5’ }];let b = [{ key: 1, name: ’name1’ }, { key: 2, name: ’name2’ }];let c = [{ key: 22, name: ’name22’ }, { key: 1, name: ’name11’ }];let akeys = a.map(x => x.key);let aname = a.map(x => x.name)let bkeys = b.map(x => x.key)//1,2let bname = b.map(x => x.name)let ckeys = c.map(x => x.key)//1,22let cname = c.map(x => x.name)ckeys.forEach(function (key, index) { if (bkeys.includes(key)) a[akeys.indexOf(key)].name = cname[ckeys.indexOf(key)] else { a[akeys.indexOf(bkeys[1])].key = key a[akeys.indexOf(bkeys[1])].name = cname[ckeys.indexOf(key)] }})console.log(a)回答6:

给你一段代码拿去想象(只适用与数组合并),将下面的代码拿到控制台输出一下就行了

function arrayExtends(){ var arrs = Array.prototype.slice.call(arguments); if(arrs.length < 2){return arrs[0]; } var save = arrs.pop(),now; while(now = arrs.pop()){for( var i = 0 , len = save.length; i < len; i++ ){ now[i] = save[i];}save = now; } return save;}arrayExtends([1,2,3,6,7],[4,5,{hello:'world'}],[{key:1,name:'zz'}]);

然后修改下适应你的需求:

function arrayExtends(){ var arrs = Array.prototype.slice.call(arguments); if(arrs.length < 2){return arrs[0]; } var save = arrs.pop(),now; while(now = arrs.pop()){for( var i = 0 , len = save.length; i < len; i++ ){ now[i] = save[i];}save = now; } var result = save.sort(function(a,b){return a.key - b.key; }); return result;}arrayExtends([{key:1,name:'zz'}],[{key:2,name:'zz'},{key:3,name:'zz'}]);

标签: JavaScript
相关文章: