1. Check if there is an item in the array that matches the condition

let arr = ['aa', "bb", "cc", 7, 88];
			
console.log(arr.some(item => {
	return (item + "").indexOf("a") > -1;
}));

//true
Copy the code

2. Check whether all items in the array meet the condition

let arr = ['aa', "bb", "cc", 7, 88];
			
console.log(arr.every(item => {
	return (item + "").indexOf("8") > -1;
}));

//false
Copy the code

3. Get the items of the array that match the criteria

let arr = ['aa', "bb", "cc", 7, 88]; console.log(arr.filter(item => { return (item + "").indexOf("8") > -1; })); / / [88]Copy the code

4. Operate on each item of the array

let arr = ['aa', "bb", "cc", 7, 88];
			
console.log(arr.map(item => {
	return item + "%";
}));

//["aa%", "bb%", "cc%", "7%", "88%"]
Copy the code

5. Sum of items in array

Let arr = [50,60,70, 80]; console.log(arr.reduce((total,item) => { return total + item; })); / / 260Copy the code

6. Array deduplication

let arr = [50, 60, 70, 80, 60, 70, 80, 60, 70, 80, 60, 70, 80];

console.log(arr.filter((item, index, arr) => {
	return arr.indexOf(item) === index;
}));

// [50, 60, 70, 80]
Copy the code

or

let arr = [50, 60, 70, 80, 60, 70, 80, 60, 70, 80, 60, 70, 80];
			
console.log(new Set(arr));

// [50, 60, 70, 80]
Copy the code

7, array sort

Let ARr = [60, 70, 80, 60, 70, 80, 60, 70, 70, 70, 80, 60, 70, 80,50, 60, 70, 80,]; console.log(arr.sort((a,b) => b-a)); // [80, 80, 80, 80, 70, 70, 70, 70, 70, 60, 60, 60, 60, 60, 50]Copy the code

or

Let ARr = [60, 70, 80, 60, 70, 80, 60, 70, 70, 70, 80, 60, 70, 80,50, 60, 70, 80,]; console.log(arr.sort((a,b) => b-a).reverse()); // [50, 60, 60, 60, 60, 70, 70, 70, 70, 80, 80, 80, 80, 80, 80]Copy the code

Shallow copy of the object

Let ARr = [60, 70, 80, 60, 70, 80, 60, 70, 70, 70, 80, 60, 70, 80,50, 60, 70, 80,]; let newArr = JSON.parse(JSON.stringify(arr)); newArr[0] = 1000; console.log(arr,newArr); //arr = [60, 70, 80, 60, 70, 80, 60, 70, 80, 50, 60, 70, 80] //newArr = [1000, 70, 80, 60, 70, 80, 60, 70, 80, 50, 60, 70, 80]Copy the code

Deep copy of an object

let copy = function(obj) {
	let newObj = (Array.isArray(obj)) ? [] : {};

	for (k in obj) {
		if (obj.hasOwnProperty(k)) {
			newObj[k] = obj[k]
		} else {
			newObj[k] = copy(obj[k]);
		}
	}

	return newObj;
}


let obj = [{
	name: "lv"
}, 12, [12, 56]];

let newObj = copy(obj);

newObj[1] = 10000;

console.log(JSON.stringify(obj,null,2),JSON.stringify(newObj,null,2));

//[
//  {
//    "name": "lv"
//  },
//  12,
//  [
//    12,
//    56
//  ]
//] [
//  {
//    "name": "lv"
//  },
//  10000,
//  [
//    12,
//    56
//  ]
//]
Copy the code