js 数组的高级用法

  1. 将值转换为数组
const newArray = (value) => (Array.isArray(value) ? value : [value]);

castArray(2); // [2] 
castArray([2,5]); // [2,5]
  1. 检查数组是否为空
const isEmpty = (arr) => !Array.isArray(arr) || arr.length === 0;

isEmpty([]); // true
isEmpty([3,6]); // false
  1. 克隆一个数组(多种方法)
const clone = (arr) => arr.slice(0);
const clone = (arr) => [...arr];
const clone = (arr) => Array.from(arr);
const clone = (arr) => arr.map((x) => x);
const clone = (arr) => JSON.parse(JSON.stringify(arr));
const clone = (arr) => arr.concat([]);
  1. 无论顺序如何比较两个数组
const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());

isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, 3, 2]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
  1. 比较两个数组
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);

isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
  1. 将对象数组转换为单个对象
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));

toObject(
    [
        { id: '1', name: 'Alpha', gender: 'Male' },
        { id: '2', name: 'Bravo', gender: 'Male' },
        { id: '3', name: 'Charlie', gender: 'Female' },
    ],
    'id'
);
/* 
{
    '1': { id: '1', name: 'Alpha', gender: 'Male' },
    '2': { id: '2', name: 'Bravo', gender: 'Male' },
    '3': { id: '3', name: 'Charlie', gender: 'Female' },
}
*/
  1. 将字符串数组转换为数字
const toNumbers = (arr) => arr.map(Number);
const toNumbers = (arr) => arr.map((x) => +x);

toNumbers(['2', '3', '4']); // [2, 3, 4]

8.按对象数组的属性计数

countBy(
      [
          { branch: 'audi', model: 'q8', year: '2019' },
          { branch: 'audi', model: 'rs7', year: '2020' },
          { branch: 'ford', model: 'mustang', year: '2019' },
          { branch: 'ford', model: 'explorer', year: '2020' },
          { branch: 'bmw', model: 'x7', year: '2020' },
      ],
      'branch'
  );
  // { 'audi': 2, 'ford': 2, 'bmw': 1 }
  1. 计算数组中某个值的出现次数
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
const countOccurrences = (arr, val) => arr.filter((item) => item === val).length;

countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3

9.创建一个累积和的数组

 const accumulate = (arr) =>arr.map(((sum) => (value) =>(sum += value))(0));
 const accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);
 
accumulate([1, 2, 3, 4]); // [1, 3, 6, 10]
  1. 清空数组
const empty = (arr) => (arr.length = 0);
arr = [];
  1. 查找数组最后一个匹配项的索引
const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index) => (predicate(curr) ? index : prev), -1);
const lastIndex = (arr, predicate) => arr.map((item) => predicate(item)).lastIndexOf(true);

lastIndex([1, 3, 5, 7, 9, 2, 4, 6, 8], (i) => i % 2 === 1); // 4
lastIndex([1, 3, 5, 7, 9, 8, 6, 4, 2], (i) => i > 6); // 5
  1. 查找数组最大项的索引
const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);

indexOfMax([1, 3, 9, 7, 5]); // 2
indexOfMax([1, 3, 7, 7, 5]); // 2
  1. 查找数组中最小项的索引
const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);

indexOfMin([6, 4, 8, 2, 10]); // 3
indexOfMin([6, 4, 2, 2, 10]); // 2
  1. 查找数组中最长字符串的长度
const findLongest = (words) => Math.max(...words.map((el) => el.length));

findLongest(['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']); // 6
  1. 通过给定的键查找数组的最大项
const maxBy = (arr, key) => arr.reduce((a, b) => (a[key] >= b[key] ? a : b), {});

const people = [
    { name: 'Bar', age: 24 },
    { name: 'Baz', age: 32 },
    { name: 'Foo', age: 42 },
    { name: 'Fuzz', age: 36 },
];
maxBy(people, 'age'); // { name: 'Foo', age: 42 }
  1. 通过给定的键查找数组的最小项
const minBy = (arr, key) => arr.reduce((a, b) => (a[key] < b[key] ? a : b), {});

const people = [
    { name: 'Bar', age: 24 },
    { name: 'Baz', age: 32 },
    { name: 'Foo', age: 42 },
    { name: 'Fuzz', age: 36 },
];
minBy(people, 'age'); // { name: 'Bar', age: 24 }
  1. 查找数组的最大项
const max = (arr) => Math.max(...arr);

console.log(max([2,45,23,98]))  //98
  1. 查找数组的最小项
const min = (arr) => Math.min(...arr);

console.log(max([2,45,23,98]))  //2
  1. 展平一个数组
const flat = (arr) =>[].concat.apply([],arr.map((a) => (Array.isArray(a) ? flat(a) : a)));
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), []);
const flat = (arr) => arr.flat();

flat(['cat', ['lion', 'tiger']]); // ['cat', 'lion', 'tiger']
  1. 生成字母字符数组
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];

 ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
  1. 合并两个数组
const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];
const merge = (a, b) => [...new Set(a.concat(b))];
const merge = (a, b) => [...new Set([...a, ...b])];
  1. 根据条件对数组进行分区
const partition = (arr, criteria) => arr.reduce((acc, i) => (acc[criteria(i) ? 0 : 1].push(i), acc), [[], []]);

partition([1, 2, 3, 4, 5], (n) => n % 2); // [[1, 3, 5], [2, 4]]

23.删除数组中的重复值

const removeDuplicate = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));

removeDuplicate(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']); //  ['h', 'e', 'w', 'r', 'd']
  1. 对数字数组进行排序
const sort = (arr) => arr.sort((a, b) => a - b);
sort([1, 5, 2, 4, 3]); // [1, 2, 3, 4, 5]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值