iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

利用30分鐘~想一個前端問題系列 第 4

利用30分鐘~想一個前端問題 [Day4]--longestItem

Takes any number of iterable objects or objects with a length property and returns the longest one.

If multiple objects have the same length, the first one will be returned. Returns undefined if no arguments are provided
Use Array.prototype.reduce(), comparing the length of objects to find the longest one.

從陣列物件 或是迭代物件找出最長的屬性,可以使用 array 的reduce 方法,比較陣列的長度,然後找出最長的元素。如回傳是 undefined 通常無提供的參數。

const longestItem = (...vals) => 
vals.reduce((a, x) => (x.length > a.length ? x : a));

EXAMPLES
longestItem('this', 'is', 'a', 'testcase'); // 'testcase'
longestItem(...['a', 'ab', 'abc']); // 'abc'
longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'
longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
longestItem([1, 2, 3], 'foobar'); // 'foobar'

記憶點

  • ES6 展開 “...” Spread Syntax

spread 可以"展開" 一個 array,這樣講很難理解,更何況後面還會加入 object 的 spread。後來想到一個最好的理解方式。

let groupA = ['小明', '杰倫', '阿姨'];
let groupB = ['老媽', '老爸'];
let groupAll = [...groupA, ...groupB];
console.log(groupAll);
console.log(...groupA);
function sum (a, b, c) {
  return a + b + c
}

const nums = [1, 2, 3]

console.log(sum(...nums))

這個東西可以用在兩個地方:

放入參數
分解 array

  • Array.prototype.reduce() 用法

陣列 (array) 的 reduce() 方法會對陣列中的每一個元素,由左至右傳入指定的函數,最後返回一個累加 (accumulator) 的值。

var suma = [0, 1, 2, 3].reduce(function(a, b) {
    return a + b;
}, 0);

// 將所有的元素值加總,最後返回結果 6
console.log(sum);

個人分析:

  1. 這邊reduce()方法,其實就是判斷元素的長度,但如果是ㄧ樣長度,他會先以第一個優先

參考資料:

https://kanboo.github.io/2018/01/26/ES6-SpreadOperator-RestOperator/


上一篇
利用30分鐘~想一個前端問題 [Day3] - includesAll
下一篇
利用30分鐘~想一個前端問題 Day5-omit
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言