1

I want to merge values of multiple arrays in one object to one array. For instance:

Object:
  - alpha: Array[3]
     0: "vatG4d6mcjKbpfuAm"
     1: "xkQrKEsfwuYPkDcdz"
     2: "GDg9chZnDGrbLXWGS"
  - bravo: Array[1]
     0: "53LEcQ5MoYXFyvktf"
  - …

The result should be:

["vatG4d6mcjKbpfuAm", "xkQrKEsfwuYPkDcdz", "GDg9chZnDGrbLXWGS", "53LEcQ5MoYXFyvktf"]

I did this with a simple for loop iterating over the elements, but I am concerned about the performance. Is this possible with a simple jQuery or underscore.js function?

Any help would be greatly appreciated.

2
  • 2
    A simple loop is probably more performant than any library call. Measure performance instead of being concerned. Commented Sep 12, 2014 at 9:41
  • In fact, jQuery's merge does exactly that. It just loops through the supplied arrays: merge:function(first,second){ for(;j<len;j++){ first[i++]=second[j]; } (And some more stuff) Commented Sep 12, 2014 at 9:47

3 Answers 3

10

There's no need to use a library for this.

For two arrays use concat:

var arr = obj.alpha.concat(obj.bravo);

For more than two arrays use a loop:

Either with concat again

var arr = [];
for (var k in obj) {
  arr = arr.concat(obj[k]);
}

Or using the push.apply method

var arr = [];
for (var k in obj) {
  arr.push.apply(arr, obj[k]);
}

DEMO

Make a function using this information so you don't need to repeat code:

function mergeObjectArrays(obj) {
  var arr = [];
  for (var k in obj) {
    arr.push.apply(arr, obj[k]);
  }
  return arr;
}

var arr = mergeObjectArrays(obj);
Sign up to request clarification or add additional context in comments.

Comments

4

with jquery you can use merge

var newArray = $.merge(array1, array2);

with underscore you can use union

var newArray = _.union(array1, array2);

1 Comment

_.union does a merge; but it will only return unique values.
1

You can concat the arrays using pure javascript like this:

var obj =
{
    alpha: ["vatG4d6mcjKbpfuAm", "xkQrKEsfwuYPkDcdz", "GDg9chZnDGrbLXWGS"],
    bravo: ["53LEcQ5MoYXFyvktf"]
};
var obj.charlie = obj.alpha.concat(obj.bravo);

// obj.charlie = ["vatG4d6mcjKbpfuAm", "xkQrKEsfwuYPkDcdz", "GDg9chZnDGrbLXWGS", "53LEcQ5MoYXFyvktf"]

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.