根据对象长度对字符串数组进行分组[关闭]

问题描述 投票:-1回答:2
var list=['abc','ab','a','c','bc','abcdef','cdf','opq']

output:-
   var object={    
            ['a','c'],
            ['ab','bc'],
            ['abc','cdf','opq'],
            ['abdcef']}
javascript ecmascript-6 ecmascript-5
2个回答
0
投票

尝试一下:

  let list = ['abc', 'ab', 'a', 'c', 'bc', 'abcdef', 'cdf', 'opq'];
  let temp = {};
  list.map(function (item) {
       !temp.hasOwnProperty(item.length) ? temp[item.length] = [item] : temp[item.length].push(item);
  });
  let output_dict = {'output': Object.values(temp)};
  console.log(output_dict)

0
投票

预期输出不正确。对象不能存储所需对象中显示的数据。您可以具有带有键值对的数组数组或对象。

在下面的示例中,使用了数组简化方法,并在回调内部检查了当前对象的长度,并创建了一个像len1,len2,len3的键,其中1,2,3 ..是当前值的长度。如果累加器对象包含诸如len1len2之类的名称的键,则将当前值推送到与该键相关的数组。否则,用该名称创建一个新密钥并添加值

var list = ['abc', 'ab', 'a', 'c', 'bc', 'abcdef', 'cdf', 'opq']

let len = 'length';
let lengthObj = list.reduce((acc, curr) => {
  const lengthKey = `len${curr.length}`
  if (acc[lengthKey]) {
    acc[lengthKey].push(curr)
  } else {
    acc[lengthKey] = [curr];

  }

  return acc;
}, {});
console.log(Object.values(lengthObj))
© www.soinside.com 2019 - 2024. All rights reserved.