查詢陣列中最短的字串 - JavaScript
我們需要編寫一個 JavaScript 函式,該函式接受一個字串陣列,並返回長度最短的字串的索引。
我們將使用一個 for 迴圈並保留長度最短的字串的索引。
示例
以下是程式碼 -
const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];
const findSmallest = arr => {
const creds = arr.reduce((acc, val, index) => {
let { ind, len } = acc;
if(val.length < len){
len = val.length;
ind = index;
};
return { ind, len };
}, {
ind: -1,
len: Infinity
});
return arr[creds['ind']];
};
console.log(findSmallest(arr));輸出
這會在控制檯中產生以下輸出 -
be
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP