数组方法使用扩展

1、Array.prototype.sort()

  1. Array.prototype.sort()默认排序是将元素转换为字符串,然后按照字符顺序进行比较
  2. Array.prototype.sort(a,b) 接受参数, a 和 b,
    如果返回负数,a 会被排在 b 之前,
    如果返回正数,a 会被排在 b 之后,
    如果返回零,a 和 b 位置不变

根据第二点拓展

1、降序排序

var numbers = [5, 10, 2, 8, 1];
numbers.sort(function(a, b) {
  return b - a;
});

console.log(numbers);
// 输出: [10, 8, 5, 2, 1]

b-a>0,则a在b之后 =>小在后,大在前
b-a<0,则a在b之前 =>大在前,小在后
因此实现降序

2、对包含对象的数组进行升序排序

var students = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 90 },
  { name: 'Charlie', score: 75 }
];

students.sort(function(a, b) {
  return a.score - b.score;
});

console.log(students);
// 输出: [ { name: 'Charlie', score: 75 }, { name: 'Alice', score: 85 }, { name: 'Bob', score: 90 } ]

3、将数组中 type===‘other’ 的项放入数组的最后

var arr = [
  { type: 'apple', value: 10 },
  { type: 'banana', value: 5 },
  { type: 'other', value: 8 },
  { type: 'other', value: 12 },
  { type: 'orange', value: 15 },
];

arr.sort((a, b) => (a.type === 'other' ? 1 : b.type === 'other' ? -1 : 0));

如果a.type == otherreturn 1 , a放后面
如果 b.type==otherreturn -1,b放后面
如果a.type b.type 都不等other,则不改变顺序
因此实现将数组中 type===‘other’ 的项放入数组的最后

2、Array.prototype.reduce()

reduce( function(){prev,item,index,array},preVal )
接收两个参数。1、回调函数;2、初始值
回调函数中接收4个参数,
prev 回调初始值 (类似求和是 sum=0) 可以设置初始值( 参数),如果不设置初始值默认是数组中的第一个元素,遍历时从第二个元素开始遍历
item 每次循环的当前元素
index 每次循环的当前下标
array 原数组,
一般用前两个参数

1、累加求和(初始值为0)

var numbers = [1, 2, 3, 4, 5];

var sum = numbers.reduce(function(acc, num) {
  return acc + num;
}, 0);

console.log(sum); // 输出: 15

2、扁平化数组

var nestedArray = [[1, 2], [3, 4], [5, 6]];

var flatArray = nestedArray.reduce(function(acc, arr) {
  return acc.concat(arr);
}, []);

console.log(flatArray); // 输出: [1, 2, 3, 4, 5, 6]

计算数组中每个元素的出现次数

var words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

var wordCount = words.reduce(function(acc, word) {
  acc[word] = (acc[word] || 0) + 1;
  return acc;
}, {});

console.log(wordCount);
// 输出: { apple: 3, banana: 2, orange: 1 }

3、汇总对象数组的属性

var data = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 22 }
];

var summary = data.reduce(function(acc, person) {
  acc.totalAge += person.age;
  acc.averageAge = acc.totalAge / data.length; //平均值
  return acc;
}, { totalAge: 0, averageAge: 0 });

console.log(summary);
// 输出: { totalAge: 77, averageAge: 25.666666666666668 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值