숫자 배열을 받는 JavaScript 함수를 작성해야 합니다. 함수는 Array.prototype.sort() 메서드를 사용하여 배열을 정렬해야 합니다. 배열을 정렬하려면 Array.prototype.reduce() 메서드를 사용해야 합니다.
다음이 우리의 배열이라고 가정해 봅시다 -
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
예시
다음은 코드입니다 -
// we will sort this array but
// without using the array sort function
// without using any kind of conventional loops
// using the ES6 function reduce()
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
const sortWithReduce = arr => {
return arr.reduce((acc, val) => {
let ind = 0;
while(ind < arr.length && val < arr[ind]){
ind++;
}
acc.splice(ind, 0, val);
return acc;
}, []);
};
console.log(sortWithReduce(arr)); 출력
이것은 콘솔에 다음과 같은 출력을 생성합니다 -
[ 98, 57, 89, 37, 34, 5, 56, 4, 3 ]