繁体   English   中英

在JavaScript中查找多维数组中最长的字符串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM