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

时间:2018-10-29 09:50:28

标签: javascript arrays string multidimensional-array string-length

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")}`)

5 个答案:

答案 0 :(得分:0)

这是您可以用来对数组中最长的字符串进行编码的方法

function findLongest(array) {
  var currentMax = "";
  for (string of array) {
      if (string.length > currentMax.length) {
          currentMax = string
      }
  }
  return currentMax;
}

然后,您可以在“项目”中的每个数组上使用此函数。 我把那个留给你^^

答案 1 :(得分:0)

您可以通过将字符串数组作为结果集来映射该数组。

ExecutorService

答案 2 :(得分:0)

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]}.`));

希望这对您有帮助!

答案 3 :(得分:0)

您需要首先在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")}`)

答案 4 :(得分:-1)

尝试下面的代码段

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}`); 
 });