Sorting Array with JavaScript reduce function

后端 未结 9 844
南方客
南方客 2020-12-01 17:49

Often I study some JavaScript interview questions, suddenly I saw a question about usage of reduce function for sorting an Array, I r

9条回答
  •  佛祖请我去吃肉
    2020-12-01 18:40

    Here is an example of the sorting an array in descending order using reduce function.

    what is the initialValue of reduce function

    In this below function the initial value is the [] which is passed as thisArg in the reduce function.

     array.reduce(function(acc,curr,currIndex,array){
            //rest of the code here
            },[]//this is initial value also known as thisArg)
    

    So basically an empty array is passed and the elements will be be pushed to this array

    The accumulator here is the empty array.

    const arr = [91, 4, 6, 24, 8, 7, 59, 3, 13, 0, 11, 98, 54, 23, 52, 87, 4];
    var m = arr.reduce(function(acc, cur) {
      // this arrVar will have the initial array
      let arrVar = arr;
      // get the max element from the array using Math.max
      // ... is spread operator
      var getMaxElem = Math.max(...arrVar);
      // in the accumulator we are pushing the max value
      acc.push(getMaxElem);
      // now need to remove the max value from the array, so that next time it 
      // shouldn't not be considered
      // splice will return a new array
      // now the arrVar is a new array and it does not contain the current
      // max value
      arrVar = arrVar.splice(arrVar.indexOf(getMaxElem), 1, '')
      return acc;
    }, []);
    console.log(m)

提交回复
热议问题