Sandesh
Sandesh

Reputation: 307

Create specific format string from array - jquery

Its simple question

I have one jquery arrary

arry = [ 'apple=1', 'apple=2', 'orange=5', 'orange=7', 'orange=9', 'guava=12', 'guava=11' ]; 

I want to convert above array into string

str = 'apple=1*2*~orange=5*7*9~guava=12*11';

Kindly help me in this...

(Actually I am looking for various interesting ways to do this)

Upvotes: 0

Views: 886

Answers (1)

David Hedlund
David Hedlund

Reputation: 129792

There are more straightforward ways, if you know you're going for that exact output, but I would find it most useful to first rearrange the array in to a proper dictionary:

var dict = {};
arry.forEach(function(item) {
   var parts = item.split('=');
   var key = parts[0];
   var value = parts[1];

   if(key in dict) {
      dict[key].push(value);
   } else {
      dict[key] = [value];
   }
});

... and then concatenate the string from that:

Object.keys(dict).map(function(key) {
   return [key, '=', dict[key].join('*')].join('');
}).join('~');

Upvotes: 3

Related Questions