2

I have an array and would like to convert it to another structure.

My array:

["DZ|47", "DZ|48", "DZ|53", "DZ|57", "AR|202", "AR|206", "AR|213", "BY|484", "BY|485", "BY|487"]

And I would like to convert this into:

{"DZ":[47,48,53,57],"AR":[202,206,213],"BY":[484,485,487]}

I'm started to write the code, but...what next?

$.each(arr, function( index, value ) {
 var idx = value.split('|');
 //arr2[idx[0]] = arr3;
});

Thanks!

R3tep
12.9k10 gold badges53 silver badges77 bronze badges
asked Apr 1, 2015 at 7:30

2 Answers 2

3
var result = {};
$.each(arr, function( index, value ) {
 var idx = value.split('|');
 if(!result[idx[0]]){
 result[idx[0]] = [];
 }
 result[idx[0]].push(idx[1]);
});
answered Apr 1, 2015 at 7:35
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Array.prototype.reduce method:

var data = ["DZ|47", "DZ|48", "DZ|53", "DZ|57", "AR|202", "AR|206", "AR|213", "BY|484", "BY|485", "BY|487"];
var result = data.reduce(function(prev, curr) {
 var split = curr.split('|');
 if (!prev[split[0]]) prev[split[0]] = [];
 prev[split[0]].push(split[1]); 
 return prev;
}, {});
alert(JSON.stringify(result));

answered Apr 1, 2015 at 7:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.