使用JavaScript排序数组减少功能 [英] Sorting Array with JavaScript reduce function

查看:243
本文介绍了使用JavaScript排序数组减少功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常学习一些 JavaScript 面试问题,我突然看到一个关于使用 reduce 函数进行排序的问题数组,我在 MDN 及其在某些 medium 文章中的用法,但排序数组非常具有创新性:

Often I study some JavaScript interview questions, suddenly I saw a question about usage of reduce function for sorting an Array, I read about it in MDN and the usage of it in some medium articles, But sorting an Array is so Innovative:

const arr = [91,4,6,24,8,7,59,3,13,0,11,98,54,23,52,87,4];

我想了很多,但我不知道如何回答这个问题,怎么一定是 reduce 回拨功能?什么是 initialValue reduce 函数?什么是累加器 currentValue 回调函数 reduce

I thought a lot, but I've no idea about how answer this question, how must be the reduce call back function? what is the initialValue of reduce function? and what are the accumulator and currentValue of call back function of reduce?

最后,这种方式是否比其他排序算法有一些好处?或者改进其他算法是否有用?

And at the end, Does this way have some benefits than other sorting algorithms? Or Is it useful to improve other algorithms?

推荐答案

在这里使用reduce是没有意义的,但是你可以使用一个新数组作为累加器并对所有元素进行插入排序:

It makes no sense to use reduce here, however you could use a new array as an accumulator and do insertion sort with all elements:

array.reduce((sorted, el) => {
  let index = 0;
  while(index < array.length && el < array[index]) index++;
  sorted.splice(index, 0, el);
  return sorted;
}, []);

这是版本没有减少:

array.sort((a, b) => a - b);






现在有一些写减速器的一般提示:


Now some general tips for writing reducers:


如何减少回调功能?

how must be the reduce call back function?

你要么采用累加器方法,然后减速器应该根据当前元素对累加器应用修改并返回它:

You either take an approach with an accumulator, then the reducer should apply a modification to the accumulator based on the current element and return it:

(acc, el) => acc

或者如果累加器和元素具有理智类型且在逻辑上相等,则无需区分他们:

Or if accumulator and the elements have the sane type and are logically equal, you dont need to distinguish them:

 (a, b) => a + b




reduce函数的initialValue是什么?

what is the initialValue of reduce function?

你应该问自己什么应该减少在空阵列上应用时的回报?


现在最重要的是:何时使用reduce? (IMO)

Now the most important: When to use reduce? (IMO)

如果要将数组的值归结为单个值或对象

If you want to boil down the values of an array into one single value or object.

这篇关于使用JavaScript排序数组减少功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆