likes
comments
collection
share

JavaScript 整理一些js常用数组的方法(不定期更新)

作者站长头像
站长
· 阅读数 364

1.排序

按对象指定的key值和指定顺序(升序or降序)排序

const people = [
    { name: 'Foo', age: 42 },
    { name: 'Bar', age: 24 },
    { name: 'Fuzz', age: 36 },
    { name: 'Baz', age: 32 },
];
/**
 * arr 需要进行排序的数组
 * key 需要进行排序的key
 * sortType 排序方式 "asc"升序,"desc"降序
 */
const orderby = (arr,key,sortType)=> {
  return arr.concat().sort((a,b) => sortType === "asc" ? a[key]-b[key] : b[key]-a[key])
}

orderby(people,"age","asc")
//  [
//      { name: 'Bar', age: 24 },
//      { name: 'Baz', age: 32 },
//      { name: 'Fuzz', age: 36 },
//      { name: 'Foo', age: 42 },
//  ]

2.判断数组是否为空

/**
 * arr 需要判断为空的数组
 */
const isEmpty = (arr) => Array.isArray(arr) && !arr.length;

isEmpty([]); // true
isEmpty([1, 2, 3]); // false

3.判断两个数组是否相等

/**
 * a和b均为数组 
 */
//方法一:
const isEqual = (a, b) => a.length === b.length && a.every((val,idx) => val === b[idx])
//方法二:
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false

后期继续更新……

转载自:https://segmentfault.com/a/1190000042257383
评论
请登录