iT邦幫忙

2023 iThome 鐵人賽

DAY 24
0
Software Development

LELECOCODE 每一天系列 第 24

Day 24: Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 24: Sort By

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.

var sortBy = function(arr, fn) {
    
};

Example 1:
Input: arr = [5, 4, 1, 2, 3], fn = (x) => x
Output: [1, 2, 3, 4, 5]

Example 2:
Input: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x
Output: [{"x": -1}, {"x": 0}, {"x": 1}]

Example 3:
Input: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1]
Output: [[10, 1], [5, 2], [3, 4]]


var sortBy = function(arr, fn) {
    return arr.sort((a, b) => fn(a) - fn(b))
};

上一篇
Day 23: Leetcode 小挑戰,30 Days of JavaScript
下一篇
Day 25: Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言