문제
Given an array arr and a function fn, return a sorted array sortedArr. You can assume fn only returns numbers and those numbers determine the sort order of sortedArr. sortedArray must be sorted in ascending order by fn output.
You may assume that fn will never duplicate numbers for a given array.
https://leetcode.com/problems/sort-by/
예시
arr을 fn의 기준에 따라 정렬시킨다.
코드
/**
* @param {Array} arr
* @param {Function} fn
* @return {Array}
*/
var sortBy = function(arr, fn) {
return arr.sort((a, b)=>fn(a)-fn(b));
};
각각 a와 b를 fn 함수를 통과시킨 뒤, 오름차순으로 정렬하였다.
728x90
'Algorithm > leetcode' 카테고리의 다른 글
[leetcode][JS] 2726. Calculator with Method Chaining (0) | 2024.02.11 |
---|---|
[leetcode][JS] 2725. Interval Cancellation (0) | 2024.02.11 |
[leetcode][JS] 2723. Add Two Promises (0) | 2024.02.06 |
[leetcode][JS] 2704. To Be Or Not To Be (0) | 2024.02.02 |
[leetcode][JS] 2703. Return Length of Arguments Passed (0) | 2024.02.02 |