目录1.数组去重2.数组去重里面的对象去重3.根据数组某个字段相同,修改另外字段值总结1.数组去重 var obj = ['麒麟','社','CC'
var obj = ['麒麟','社','CC','DD','麒麟','社','11',11]
//定义一个新的数组
var s = [];
//遍历数组
for(var i=0;i<obj.length;i++){
if(s.indexOf(obj[i]) == -1){ //判断在s数组中是否存在,不存在则push到s数组中
s.push(obj[i]);
}
}
console.log(s);
var old_data = [
{ name:'ccc', age:'18' },
{ name:'peng', age:'18' }, //去除peng重复
{ name:'aaa', age:'18' },
{ name:'peng', age:'18' },
]
// 方法1:利用对象访问属性的方法,判断对象中是否存在key
var result = [];
var obj = {};
old_data.forEach(function (data) {
if(!obj[data.name]){
result.push(data);
obj[data.name] = true;
}
})
console.log(result);
var oldData = [
{ name:'cccc', age:'5656' },
{ name:'cccc', age:'22DDDsada' },
{ name:'cccc', age:'22dddsada' },
{ name:'aaaa', age:'32' },
{ name:'aaaa', age:'2dasdasdas2' },
]
var newArr = [];
for (var i = 0; i <oldData.length; i++) {
var item = oldData[i];
var isExists = false;
for (var j = 0; j < newArr.length; j++) {
var item2 = newArr[j];
if (item2.name == item.name) {
isExists = true;
break;
}
}
if (isExists) {
// 这里找到相同的,更改一样的
if(item.name == 'cccc'){
item.age = '222222'
item2.age = '222222'
}else{
item.age = '3333'
item2.age = '3333'
}
newArr.push(item2);
continue;
}
newArr.push(item);
}
console.log(newArr)
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: JavaScript 数组去重详解
本文链接: https://lsjlt.com/news/135695.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0