I want to merge arrays a little bit different way. I have 2 or more arrays like:
var array1 = ["apple", "banana"];
var array2 = ["apple", "apple", "orange"];
I want the output:
var array3 = ["apple", "apple", "banana", "orange"];
So if any given array has a variable in it more than once, merge algorithm should keep all of them from that array.
I saw some code that prevents duplication but it gives outputs like this:
var array3 = ["apple", "banana", "orange"];
for more example:
var arr1 = [1,2,3,4];
var arr2 = [1,1,2,4,5,5,5];
var arr3 = [1,3,3,5,5];
I want the output:
var array4 = [1,1,2,3,3,4,5,5,5];
How can I do this?
Here's one way to do it by counting the occurrences of each item in each array:
var arr1 = [1,2,3,4];
var arr2 = [1,1,2,4,5,5,5];
var arr3 = [1,3,3,5,5];
function joinCommon(/* list of arrays */) {
var arr, arrayCounts, masterList = {}, item, output;
// for each array passed in
for (var i = 0; i < arguments.length; i++) {
arr = arguments[i];
arrayCounts = {};
// iterate each array
for (var j = 0; j < arr.length; j++) {
item = arr[j];
if (!arrayCounts[item]) {
arrayCounts[item] = 1;
} else {
++arrayCounts[item];
}
// now keep master list and master counts
if (!masterList[item]) {
masterList[item] = {cnt: 1, val: item};
} else {
masterList[item].cnt = Math.max(masterList[item].cnt, arrayCounts[item]);
}
}
}
// now output result
output = [];
for (var i in masterList) {
for (var j = 0; j < masterList[i].cnt; j++) {
output.push(masterList[i].val);
}
}
return output;
}
var results = joinCommon(arr1, arr2, arr3);
Working demo: http://jsfiddle.net/jfriend00/dtn6zw4m/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With