0

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)

2
  • 3
    Did you attempt it yourself or no? Commented May 15, 2013 at 9:27
  • Yep and its working as per expectation... Commented May 16, 2013 at 7:41

1 Answer 1

3

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('~');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.