1、找出总和、最小值和最大值

const array  = [5,4,7,8,9,2];
//1、求和
array.reduce((a,b) => a+b);
// 输出: 35

//2、求最大值
array.reduce((a,b) => a>b?a:b);
// 输出: 9

//3、求最小值
array.reduce((a,b) => a<b?a:b);
// 输出: 2

2、对字符串、数字或对象数组进行排序

//1、排序字符串数组
const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// 输出 ["Joe", "Kapil", "Musk", "Steve"]
stringArr.reverse();
// 输出 ["Steve", "Musk", "Kapil", "Joe"]

//2、排序数字数组
const array = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// 输出 [1, 5, 10, 25, 40, 100]
array.sort((a,b) => b-a);
// 输出 [100, 40, 25, 10, 5, 1]

//3、对象数组排序
const objectArr = [
{ first_name: 'Lazslo', last_name: 'Jamf' },
{ first_name: 'Pig', last_name: 'Bodine' },
{ first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// 输出
(3) [{}, {}, {}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
length: 3

3、从数组中过滤出虚假值

Array 类中的 filter 方法使用目的是移除所有的 ”false“ 类型元素 0,undefined,null,false,“”,''可以很容易地通过以下方法省略

const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);
// 输出
(3) [3, 6, 7]

4、删除重复值

//方式一
const array = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);

// 方式二
const nonUnique = [...new Set(array)];
// 输出: [5, 4, 7, 8, 9, 2]

5、创建计数器对象或映射

let string = 'kapilalipak';
//方式一
const table={};
for(let char of string) {
table[char]=table[char]+1 || 1;
}
// 输出
{k: 2, a: 3, p: 2, i: 2, l: 2}

//方式二
const countMap = new Map();
for (let i = 0; i < string.length; i++) {
if (countMap.has(string[i])) {
countMap.set(string[i], countMap.get(string[i]) + 1);
} else {
countMap.set(string[i], 1);
}
}
// 输出
Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}

6、合并多个对象

const user = { 
name: 'Kapil Raghuwanshi',
gender: 'Male'
};
const college = {
primary: 'Mani Primary School',
secondary: 'Lass Secondary School'
};
const skills = {
programming: 'Extreme',
swimming: 'Average',
sleeping: 'Pro'
};

const summary = {...user, ...college, ...skills};

// 输出
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"

7、 单行回文检查

function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
checkPalindrome('naman'); //判断是不是回文
// 输出: true