Search code examples
javascriptecmascript-6ecmascript-5

Grouping string array based on object length


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

output:-
   var object={    
            ['a','c'],
            ['ab','bc'],
            ['abc','cdf','opq'],
            ['abdcef']}

Solution

  • Try this :

      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)