Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  75] [ 7]  / answers: 1 / hits: 196539  / 14 Years ago, thu, september 2, 2010, 12:00:00

Say I have an array of [34, 35, 45, 48, 49] and another array of [48, 55]. How can I get a resulting array of [34, 35, 45, 48, 49, 55]?


More From » arrays

 Answers
8

If you don't need to keep the order, and consider 45 and 45 to be the same:





function union_arrays (x, y) {
var obj = {};
for (var i = x.length-1; i >= 0; -- i)
obj[x[i]] = x[i];
for (var i = y.length-1; i >= 0; -- i)
obj[y[i]] = y[i];
var res = []
for (var k in obj) {
if (obj.hasOwnProperty(k)) // <-- optional
res.push(obj[k]);
}
return res;
}

console.log(union_arrays([34,35,45,48,49], [44,55]));




[#95726] Monday, August 30, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marisela

Total Points: 103
Total Questions: 105
Total Answers: 102

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;