[英]Finding the longest strings within a multidimentional array in JavaScript
let lists = ["Grocery", "Clothing", "Furniture"]; let items = [ [ "tomatoes", "cheese", "bread", "ham" ], [ "shirt", "jacket", "jeans" ], [ "sofa", "carpet", "bed" ] ];
所以我有這兩個數組。 其中“項目”數組屬於列表的每個數組。 例如,項[0]屬於列表[0]等。
試圖從數組中獲取最長的字符串,我嘗試了這個,但是它不起作用....
let longestString = (list) => { lists[items.reduce((a, b) => a.length > b.length ? a : b)]; } console.log('Clothing's longest item is: ${longestString("Clothing")}`)
這是您可以用來對數組中最長的字符串進行ding的方法
function findLongest(array) {
var currentMax = "";
for (string of array) {
if (string.length > currentMax.length) {
currentMax = string
}
}
return currentMax;
}
然后,您可以在“項目”中的每個數組上使用此函數。 我把那個留給你^^
您可以通過將字符串數組作為結果集來映射該數組。
var lists = ["Grocery", "Clothing", "Furniture"], items = [["tomatoes", "cheese", "bread", "potatoes"], ["shirt", "jacket", "jeans"], ["sofa", "carpet", "bed"]], result = items.map(a => a.reduce((r, v) => { if (!r || r[0].length < v.length) { return [v]; } if (r[0].length === v.length) { r.push(v); } return r; }, undefined)); lists.forEach((l, i) => console.log(`${l}'s longest item${result[i].length === 1 ? ' is' : 's are'} ${result[i].join(', ')}.`)); console.log(result);
let lists = ["Grocery", "Clothing", "Furniture"]; let items = [ [ "tomatoes", "cheese", "bread", "potatoes" ], [ "shirt", "jacket", "jeans" ], [ "sofa", "carpet", "bed" ] ]; var listsObj = lists.reduce( (obj, k, idx) => { obj[k] = items[idx].reduce( (res, i) => (res.length > i.length ? res : i), '' ); return obj; }, {} ); lists.forEach(k => console.log(`${k}'s longest item is: ${listsObj[k]}.`));
希望這對您有所幫助!
你需要先找到在索引lists
對應於給定的list
,然后再應用reduce
特定子陣列上的呼叫:
const lists = ["Grocery", "Clothing", "Furniture"]; const items = [["tomatoes", "cheese", "bread", "potatoes"], ["shirt", "jacket", "jeans"], ["sofa", "carpet", "bed"]]; const longestString = (list) => items[lists.indexOf(list)].reduce((a, b) => a.length > b.length ? a : b); console.log(`Clothing's longest item is: ${longestString("Clothing")}`)
但是,如果將列表名稱和相應的項存儲在一起 ,則將是一個更好的數據結構:
const lists = { Grocery: ["tomatoes", "cheese", "bread", "potatoes"], Clothing: ["shirt", "jacket", "jeans"], Furniture: ["sofa", "carpet", "bed"] }; const longestString = (list) => lists[list].reduce((a, b) => a.length > b.length ? a : b); console.log(`Clothing's longest item is: ${longestString("Clothing")}`)
嘗試下面的代碼片段
let lists = ["Grocery", "Clothing", "Furniture"]; let items = [ [ "tomatoes", "cheese", "bread", "ham" ], [ "shirt", "jacket", "jeans" ], [ "sofa", "carpet", "bed" ] ]; lists.forEach( (category, index) => { let longest = items[index].reduce(function (a, b) { return a.length > b.length ? a : b; }); console.log(`${category}'s longest item is: ${longest}`); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.