JavaScript - Combine two arrays item by item - javascript

I have two arrays of arrays where the first contains the location name and the second contains the location latitude and longitude values. Each item in each array corresponds to it's counterpart in the other and both arrays have the same number of items like so:
var arr1 = [['Location #1'],['Location #2']];
var arr2 = [['36.1978319','-83.02365759999999'],['38.679842','-121.7457402']];
What I need is a combined array of the two sets of items, but not concatenated like so:
var arr3 = [['Location #1','36.1978319','-83.02365759999999'],
['Location #2','38.679842','-121.7457402']];
The only way I can think of doing this would be with like a combined for loop, but I can't get the syntax correct and not sure this is even possible... something like this:
for ((var a = 0; a < arr1.length; a++) && (var b = 0; b < arr2.length; b++)) {
arr3.push(arr1[a] + ',' + arr2[b]);
}
Is there a way to solve this problem with pure javascript?

I suggest Array.map for its shortness:
var arr1 = [['Location #1'], ['Location #2']];
var arr2 = [['36.1978319', '-83.02365759999999'], ['38.679842', '-121.7457402']];
var combined = arr1.map((element, i) => element.concat(arr2[i]));
console.log(combined);
For a more generic solution (combining an arbitrary number of arrays), refer to Javascript equivalent of Python's zip function

If the two arrays really are equal in length, and correspond in index. This is all you need:
for (var a = 0; a < arr1.length; a++) {
arr3.push(arr1[a] + ',' + arr2[a]);
}

You are trying to combine 2 contors inside a for loop :).
You want to do this:
var resultArray = new Array();
for (var i = 0; i < arr1.length; i++) {
resultArray.push([arr1[i], arr2[i][0], arr2[i][1]]);
}

Related

How to generate an array with repeated string javascript

How to generate an array with function like this?
var name = ["monkey","monkey"..."horse","horse",..."dog","dog",..."cat","cat"...]​
In my real case, I may have to repeat each name 100 times..
Assuming that you already have that words in a array try this code:
var words = ["monkey", "hourse", "dog", "cat"];
var repeatWords = [];
for(var i = 0; i < words.length; i++)
{
for(var j = 0; j < 100; j++)
{
repeatWords.push(words[i]);
}
}
You can try this, specifying the words to be used, and the times to create the array you need.
var neededWords = ["Cat", "Hourse", "Dog"];
var finalArray = [];
var times = 10;
for (var i = 0; i < neededWords.length; i++) {
for (var n = 0; n < times; n++) {
finalArray.push(neededWords[i]);
}
}
console.log(finalArray);
Hope that helps!
If I understood correctly you need a function that takes as an argument a collection of items and returns a collection of those items repeated. From your problem statement, I assumed that the repetition has to be adjusted by you per collection item - correct me if I am wrong.
The function I wrote does just that; it takes an object literal {name1:frequency1,name2:frequency2..} which then iterates over the keys and pushes each one as many times as indicated by the associated frequency in the frequencyMap object.
function getRepeatedNames( frequencyMap ) {
var namesCollection = [];
Object.keys(frequencyMap).forEach(function(name,i,names){
var freq = frequencyMap[name];
freq = (isFinite(freq)) ? Math.abs(Math.floor(freq)) : 1;
for (var nameCounter=0; nameCounter<freq; nameCounter++) {
namesCollection.push(name);
}
});
return namesCollection;
}
Non-numeric values in the frequency map are ignored and replaced with 1.
Usage example: If we want to create an array with 5 cats and 3 dogs we need to invoke
getRepeatedNames({cat: 2, dog: 3}); // ["cat","cat","dog","dog","dog"]

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

make a left outer join in javascript

I have an array of objects in javascript (D3) and I need to remove every object of which a certain attribute is present in another array of objects attribute,
i.e. a left outer join
(source: tazindeed.co.uk)
I managed to do it myself with 2 loops but it's quite slow.
And I don't know how to make it faster.
for (var i = 0; i < data1.length; i++) {
for (var j = 0; j < data2.length; j++) {
if (data2[j].attr3 == data1[i].attr4) {
data2.splice(j,1);
}
}
}
data1.length~2k and data2.length~10k
I know this has approximately been asked here but it's been almost 2 years and the solutions use external libraries.
I'm just curious to learn if there is a better method with javascript (or jQuery or D3, which I already use)
Thank you for your help !
You need a fast lookup for the values that exist in data1, so make a map using an object:
var map = {};
for (var i = 0; i < data1.length; i++) {
map[data1[i].attr4] = 1;
}
Then you can loop throught the items in data2 and filter them:
var result = [];
for (i = 0; i < data2.length; i++) {
if (!(data2[i].attr3 in map)) {
result.push(data2[i]);
}
}
Maybe not faster but more readable
const left = ['1', '2', '7']
const right = ['1', '3', '5', '9']
const result = left.filter((x) => !right.includes(x))
You could use Array.filter (see MDN) or Array.map for that I suppose:
var array1 = [1,2,3,4,5,6,7,8,9],
array2 = [3,4,5,6],
fltr = array1.filter( function(v) {return this.indexOf(v) < 0;}, array2),
map = array1.map(
function(v) {
var exists = this.indexOf(v);
return [v, (this[exists] || 'null')].join(', ');},
array2),
result = document.querySelector('#result');
fltr.unshift('<u>array1</u>');
map.unshift('<u>array1, array2</u>');
result.innerHTML = ['<b>filtered</b>\n',
fltr.join('\n'),
'\n\n<b>mapped</b>\n',
map.join('\n')].join('');
<pre id="result"></pre>

Corresponding arrays (Javascript)

So let's say I have two arrays
var x = [1,2,3,4,5,6]
var y = [A,B,C,D,E,F]
I want to display the values of the variables together based on their index location/value. eg: so A corresponds with 1, B corresponds with 2, etc, like so:
A,1
B,2
C,3
etc
How can I display them together based on their index location?
Assuming they always match, just loop one and reference both:
for (var i = 0; i < x.length; i++) {
console.log(y[i] + "," + x[i]);
}

Javascript : How should I run one `for`, for two arrays?

I have:
var array1 = [];
var array2 = [];
array1 contains 1,2
array2 contains 3,4
And I want to do this:
for(var a in array1){
for(var b in array2){
doSomething(array1[a],array2[b]);
}
}
But the problem is that function doSomething() runs twice for each array because of the two for's.
How should run it just once but with all of the arrays?
EDIT
The numbers are not in ascending order! In my real project they are ID's what can be any number in any order.
You shouldn't use for..in for looping through arrays. Use an index variable:
for (var i = 0, len = array1.length; i < len; i++) {
doSomething(array1[i], array2[i]);
}
This of course assumes they're the same length.
I think this is what you're after:
for(var i=0; i<array1.length; i++){
doSomething(array1[i],array2[i]);
}
This loops through both arrays, using the first for the length, and taking the element at the same index in both for each doSomething() call.
If you are sure that both arrays have the exact same length, you can do the following:
for (var i = 0; i < array1.length; i++) {
doSomething(array1[i], array2[i]);
}
It looks like you want to concatenate two arrays together. Use the concat() function:
var jointArray = array1.concat(array2);
for(var i=0; i < jointArray.length; i++) {
doSomething(jointArray[i]);
}
See:
http://www.w3schools.com/jsref/jsref_concat_array.asp
This if array arent same length
for (var i = 0, i < (array1.length <= array2.length ? array1.length : array2.length); i++) {
doSomething(array1[i], array2[i]);
}
DoSomething will run 4 times. If you want it to just run through the values both list together, remove the second for loop and replace b in DoSomething with a.

Categories

Resources