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!

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]);
});
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));

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.