js操作数组、对象排序、去重、合并
去重
数组
arr.includes(指定元素(必填),指定索引值(可选,默认值为0) ),有值返回true,没有则返回false
var arr = [-1,0,8,-3,-1,5,5,7]
function unique (arr) {
let arr1 = []
for (var i = 0; i < arr.length; i++) {
if (!arr1.includes(arr[i])) {
arr1.push(arr[i])
}
}
return arr1
}
利⽤数组的filter⽅法去重
var arr = [1,2,8,9,5,8,4,0,4];
/*
模拟: 原始数组:[1,2,8,9,5,8,4,0,4]
索引值:0,1,2,3,4,5,6,7,8
伪新数组:[1,2,8,9,5,8,4,0,4]
使⽤indexOf⽅法到数组中的元素在元素在中第⼀次出现的索引值
索引值:0,1,2,3,4,2,6,7,6
返回前后索引值相同的元素:
新数组:[1,2,8,9,5,4,0]
*/
function unique( arr ){
// 如果新数组的当前元素的索引值 == 该元素在原始数组中的第⼀个索引,则返回当前元素
return arr.filter(function(item,index){
js合并两个数组
return arr.indexOf(item,0) === index;
});
}
console.log(unique(arr));    //  1, 2, 8, 9, 5, 4, 0
利⽤数组的indexOf⽅法去重
var arr =[1,-5,-4,0,-4,7,7,3];
function unique(arr){
var arr1 = [];      // 新建⼀个数组来存放arr中的值
for(var i=0,len=arr.length;i<len;i++){
if(arr1.indexOf(arr[i]) === -1){
arr1.push(arr[i]);
}
}
return arr1;
}
console.log(unique(arr));    // 1, -5, -4, 0, 7, 3
ES6 new Set
var arr= [1,1,2,3,4,5,3,8]
console.log(Array.from(new Set(arr)))
(6) [1, 2, 3, 4, 5, 8]
对象
reduce 对象去重
let person = [
{id: 0, name: "张三"},
{id: 1, name: "张三2"},
{id: 2, name: "⼩张三3"},
{id: 3, name: "⼩张三4"},
{id: 1, name: "⼩张三5"},
{id: 2, name: "⼩张三6"},
];
let obj = {};
let peon = duce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(peon);
0: {id: 0, name: "张三"}
1: {id: 1, name: "张三2"}
2: {id: 2, name: "⼩张三3"}
3: {id: 3, name: "⼩张三4"}
排序
数组
var arr= [3,4,5,7,88,2,23]
arr.sort((a, b) => { return a- b})//升序
arr.sort((a, b) => { return b- a})//降序
对象
var person = [
{ name: "张三1", age: 12 },
{ name: "张三2", age: 22 },
{ name: "张三3", age: 5 },
{ name: "张三4", age: 25 }
]
person.sort((a, b) => { return a.age - b.age })//升序
person.sort((a, b) => { return b.age - a.age })//降序
数组合并去重
let arr1 = [3,5,2,3,6];
let arr2 = [5,2,4,6,8,7,9,2];
let arr = at(arr2);  //合并数组
let arrNew= new Set(arr); //通过set集合去重
console.log("arrNew",Array.from(arrNew)); //将set集合转化为数组
数组对象合并去重
let json1 = [
{ id: 1, name: "aaa" },
{ id: 2, name: "bbb" },
{ id: 3, name: "ccc" },
]
let json2 = [
{ id: 1, name: "aaa" },
{ id: 2, name: "bbb" },
{ id: 4, name: "ddd" },
]
let json = at(json2); //两个数组对象合并
let obj = {};
let peon = duce((cur, next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
}, []) //设置cur默认类型为数组,并且初始值为空的数组
console.log(peon);
VM33:18
(4) [{…}, {…}, {…}, {…}]
0: {id: 1, name: "aaa"}
1: {id: 2, name: "bbb"}
2: {id: 3, name: "ccc"}
3: {id: 4, name: "ddd"}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。