手记

javascript数组的几个常用姿势

前言

本文将分享几个在项目中常用的数组方法~

原文地址: https://github.com/webfansplz/blog/issues/4

不定期有干货更新哦,欢迎watch,star!

1.数组排序
  const sortAry = [1, 5, 4, 3, 2, 6, 7];

  1.按数组元素大小从小到大进行排序

  sortAry.sort((a, b) => a - b); //[1, 2, 3, 4, 5, 6, 7]

  2.按数组元素大小从大到小进行排序

  sortAry.sort((a, b) => b - a); //[7, 6, 5, 4, 3, 2, 1]

  const sortId = [
    { id: 3, name: "c" },
    { id: 1, name: "a" },
    { id: 2, name: "b" }
  ];

  3. 按数组元素的id从小到大进行排序

  sortId.sort((a, b) => a.id - b.id);

  //[{ id: 1, name: "a"},{id: 2, name: "b"},{id: 3, name: "c"}]

  4.按数组元素的id从大到小进行排序

  sortId.sort((a, b) => b.id - a.id); 

  //[{ id: 3, name: "c" },{ id: 2, name: "b" },{ id: 1, name: "a" }]
};
2.数组去重
  const uniqAry = ary => Array.from(new Set(ary));

  const uniqAry2 = ary => ary.filter((v, k) => ary.indexOf(v) == k);

  const ary = [1, 2, 1, 2, 3, 4, 3];

  uniqAry(ary)   //[1,2,3,4]

  uniqAry2(ary)  //[1,2,3,4]
3.数组深拷贝
 const copyAry = [1, 2, 3, 4];

 const ary = [].slice.apply(copyAry);

 ary.push(5);

 console.log(ary);     //[1, 2, 3, 4, 5]

 console.log(copyAry); //[1, 2, 3, 4]

 const ary2 = JSON.parse(JSON.stringify(copyAry));

 ary2.push(5);

 console.log(ary2);   //[1, 2, 3, 4, 5]

 console.log(copyAry); //[1, 2, 3, 4]
4.数组等份分割
const ary = [1, 2, 3, 4, 5, 6, 7];

const splitAry = (ary, size) => {
  let i = Math.ceil(ary.length / size),
    count = 0,
    box = [];
  while (count < i) {
    let s = count * size;
    box.push(ary.slice(s, s + size));
    count++;
  }
  return box;
};

console.log(splitAry(ary, 3)); //[[1,2,3],[4,5,6],[7]]

console.log(splitAry(ary,2)); // [[1,2],[3,4],[5,6],[7]]
5.数组扁平化
//二维数组扁平化

const ary = [[1, 2], [3, 4], [5, 6]];

const flatten = ary => ary.reduce((a, b) => [...a, ...b]);

console.log(flatten(ary)); //[1, 2, 3, 4, 5, 6]

//多维数组扁平化

const ary2 = [[1, [2, 3]], [4, [5, [6, 7]]]];

const flattenS = ary =>
  ary.reduce((a, b) => a.concat(Array.isArray(b) ? flattenS(b) : b), []);

console.log(flattenS(ary2)); //[1, 2, 3, 4, 5, 6, 7]
0人推荐
随时随地看视频
慕课网APP