This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 9 years ago.
I have two arrays in javascript:
var array1 = ["a","b","c"];
var array2 = ["e","f","g"];
And I want the resulting array to be like this:
array3 = ["a","e","b","f","c","g"];
Any way to do this?
Will a straightforward loop do it?
array3 = new Array();
for(var i = 0; i < array1.length; i++)
{
array3.push(array1[i]);
array3.push(array2[i]);
}
You can try with concat() method:
var array1 = ["a","b","c"];
var array2 = ["e", "f","g"];
var array3 = array1.concat(array2); // Merges both arrays
For your specific requirement, you have to follow this:
function mergeArrays(a, b){
var ret = [];
for(var i = 0; i < a.length; i++){
ret.push(a[i]);
ret.push(b[i]);
}
return ret;
}
This should work:
function zip(source1, source2){
var result=[];
source1.forEach(function(o,i){
result.push(o);
result.push(source2[i]);
});
return result
}
Look http://jsfiddle.net/FGeXk/
It was not concatenation, so the answer changed.
Perhaps you would like to use: http://underscorejs.org/#zip
Related
This question already has answers here:
Javascript equivalent of Python's zip function
(24 answers)
Closed 6 years ago.
Suppose we have two arrays
var arrayOne = [21.03.2016, 22.03.2016, 23.03.2016]
var arrayTwo = [23.45, 34.45, 25.76]
How can we join it so that it becomes
var joinedResultOfOneandTwo = [[21.03.2016, 23.45],
[22.03.2016, 34.45],
[23.03.2016, 25.76]]
Note It is important that we do not change the type of variables both of them should be numbers.
This is what I have tried:
for (var i = 0; i < arrayOne.length; i++) {
var clintonValues = arrayOne[i].concat(arrayTwo[i])
}
returns:
TypeError: arrayOne[i].concat is not a function
Here is an example
var arrayOne = ['21.03.2016', '22.03.2016', '23.03.2016']
var arrayTwo = ['23.45', '34.45', '25.76']
var joinedResultOfOneandTwo = [];
for (i = 0; i < arrayOne.length; i++) {
joinedResultOfOneandTwo.push([arrayOne[i], arrayTwo[i]]);
}
console.log(joinedResultOfOneandTwo);
Did you try .concat? It will join two arrays into one
var arrayOne = [21.03.2016, 22.03.2016, 23.03.2016];
var arrayTwo = [23.45, 34.45, 25.76];
arrayOne.concat(arrayTwo);//join arrayTwo into arrayOne
This question already has answers here:
Declare variables programmatically?
(3 answers)
Closed 7 years ago.
A user dynamically chooses a value X. Based on the value, X, I want to create unique empty arrays. How would I go about that?
For example, user chooses 4.
I want the following output:
var array1 = [];
var array2 = [];
var array3 = [];
var array4 = [];
Is there a way to properly doing this?
You can specify the name of a property on an object using the square brackets with a string input:
var obj = {};
var numberOfArrays = 4;
for(var i = 1; i <= numberOfArrays; i++){
obj['array' + i] = []; // Specify the name of the array property
}
console.log(obj); // Logs an object which has 4 empty arrays
Just to complement Steven`s answer, you could also create an array of arrays:
var numberOfArrays = X;
var arr = [];
for(var i = 0; i < numberOfArrays; i++){
arr.push(new Array());
}
This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 7 years ago.
I have this JavaScript array with length 129.
var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]
I would like to find how many times those names appeared in an array and store that information in an array like this:
var counter = [2, 5, 7, ..]
where Karri occured in fullnames array 2 times, Ismo occured 5 times etc. Any ideas about how to do it?
This is the best - and simple - way I can think of:
var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};
for (var i = 0; i < fullnames.length; i++)
{
if (!counts.hasOwnProperty(fullnames[i]))
{
counts[fullnames[i]] = 1;
}
else
{
counts[fullnames[i]]++;
}
}
console.log(counts);
Original Fiddle.
Using an array to store the counts doesn't makes much sense, so I used an object instead.
I am assuming that fullnames is array of strings. If so, you can do it like so:
var occurences = { };
for (var i = 0; i < fullnames.length; i++) {
if (typeof occurences[fullnames[i]] == "undefined") {
occurences[fullnames[i]] = 1;
} else {
occurences[fullnames[i]]++;
}
}
console.log(occurences); // Prints out something like: {"Karri": 2, "Ismo": 5, ...}
var fullnames = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
var counts = [];
fullnames.forEach(function(_item) {
if(typeof counts[_item] === 'undefined') counts[_item] = 1;
else counts[_item]++;
});
var result = [];
for(i in counts) result.push(counts[i]);
console.log(result);
// outputs [3, 3, 5]
This question already has answers here:
How to find elements in array2 that are not in array1?
(2 answers)
Closed 8 years ago.
I have a array a=[1,2,3,4,5] b=[3,4,5,6,7]
Here i want values of array a [1,2] and array b [6,7] and stored in diff arrays like below.
c=[1,2]
d=[6,7]
Thanks in Advance.
its like a=[chkbx_705_49,chkbx_706_49,chkbx_707_49,chkbx_708_49,chkbx_709_49,chkbx_710_49,chkbx_711_49,chkbx_712_49,chkbx_714_49,chkbx_705_50,chkbx_706_50,chkbx_707_50,chkbx_708_50,chkbx_709_50,chkbx_710_50,chkbx_711_50,chkbx_705_51,chkbx_706_51,chkbx_707_51,chkbx_708_51,chkbx_711_51,chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53]
b= [chkbx_705_49,chkbx_705_50,chkbx_705_51,chkbx_705_52,chkbx_705_53,chkbx_706_49,chkbx_706_50,chkbx_706_51,chkbx_706_52,chkbx_706_53,chkbx_707_49,chkbx_707_50,chkbx_707_51,chkbx_708_49,chkbx_708_50,chkbx_708_51,chkbx_709_49,chkbx_709_50,chkbx_710_49,chkbx_710_50,chkbx_711_49,chkbx_711_50,chkbx_711_51,chkbx_712_49]
here i deleted chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53 checkbox values from array a
and added chkbx_705_52,chkbx_705_53,,chkbx_706_52,chkbx_706_53 added in array b.
So i want c = chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53
d = chkbx_705_52,chkbx_705_53,,chkbx_706_52,chkbx_706_53
When a member of A also exists in B, delete in both:
var a = [1,2,3,4,5];
var b = [3,4,5,6,7];
var c = a.slice();
var d = b.slice();
var len = c.length;
while(len--) {
var idx = d.indexOf(c[len]);
if (idx > -1) {
c.splice(len, 1);
d.splice(idx, 1);
}
}
However, you didn't say whether there are duplicated members, so I assume no and do it in the simplest way, just to give you a thought of solution.
You can get it like below:
var array1 = [1,2,3,4,5];
var array2 = [3,4,5,6,7];
var foo1 = [], foo2=[];
var i = 0;
jQuery.grep(array1, function(el) {
if (jQuery.inArray(el, array2) == -1) foo1.push(el);
i++;
});
jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) foo2.push(el);
i++;
});
alert(" the difference is " + foo1);
alert(" the difference is " + foo2);
This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 6 years ago.
I want to convert a 2D JavaScript array to a 1D array, so that each element of the 2D array will be concatenated into a single 1D array.
Here, I'm trying to convert arrToConvert to a 1D array.
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
console.log(get1DArray(arrToConvert)); //print the converted array
function get1DArray(2dArr){
//concatenate each element of the input into a 1D array, and return the output
//what would be the best way to implement this function?
}
Use the ES6 Spread Operator
arr1d = [].concat(...arr2d);
Note that this method is only works if arr2d has less than about 100 000 subarrays. If your array gets larger than that you will get a RangeError: too many function arguments.
For > ~100 000 rows
arr = [];
for (row of table) for (e of row) arr.push(e);
concat() is too slow in this case anyway.
The Underscore.js way
This will recursively flatten arrays of any depth (should also work for large arrays):
arr1d = _.flatten(arr2d);
If you only want to flatten it a single level, pass true as the 2nd argument.
A short < ES6 way
arr1d = [].concat.apply([], arr2d);
Try .concat():
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
var newArr = [];
for(var i = 0; i < arrToConvert.length; i++)
{
newArr = newArr.concat(arrToConvert[i]);
}
console.log(newArr);
Try .reduce()
var test2d = [
["foo", "bar"],
["baz", "biz"]
];
var merged = test2d.reduce(function(prev, next) {
return prev.concat(next);
});
console.log(merged)
Source: http://jsperf.com/2-dimensional-array-merge
How about:
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
function get1DArray(arr){
return arr.join().split(",");
}
console.log(get1DArray(arrToConvert));
http://jsfiddle.net/JRR4J/
var arrToConvert = [[0,0,1],[2,3,3],[4,4,5]];
var modifiedArray = arrToConvert.map(function(array){
return array[0]+array[1]+array[2];
});
Another Example
var passengers = [
["Thomas", "Meeks"],
["Gregg", "Pollack"],
["Christine", "Wong"],
["Dan", "McGaw"]
];
var modifiedNames = passengers.map(function(convArray){
return convArray[0]+" "+convArray[1];
});
var arrToConvert = [[0, 0, 1], [2, 3, 3], [4, 4, 5]];
function get1DArray(arr){
var result = new Array();
for (var x = 0; x < arr.length; x++){
for (var y = 0; y < arr[x].length; y++){
result.push(arr[x][y])
}
}
return result
}
alert (get1DArray(arrToConvert))
http://jsfiddle.net/Saturnix/ReeqQ/