add elements of two arrays - the best way - javascript

var a = "1:2:3:4";
var b = "0:1:5:2";
I want at the end:
var c = "1:3:8:6";
meaning, the numbers are summed by column.
my solution is:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
and here again another loop over b_arr
}
eeh ok, I dont have solution.. what is the cutest way to do this?

You could just map it and return the added values ?
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = a.split(':').map(function(x, i) {
return (+x) + (+b.split(':')[i]);
}).join(':');
document.body.innerHTML = '<pre>' + c + '</pre>';
or splitting outside the map
var c = (function(y) {
return a.split(':').map(function(x, i) {
return (+x) + (+y[i]);
}).join(':')
})(b.split(':'));

Building on my comment, you can use i to index both the arrays:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i=0;i<a_arr.length;i++){
c_arr.push(parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10));
}
//And use join to get the final result
var c = c_arr.join(":");

You can use index i to add the simply use join()
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = [];
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
c[i] = parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10); //Add using index
}
console.log(c.join(':')); //Use Join

http://jsfiddle.net/fLavfcjz/1/
Use .map() and don't forget parseInt() otherwise the numbers will considered as strings.
var a = "1:2:3:4";
var b = "0:1:5:2";
var arrayA = a.split(':');
var arrayB = b.split(':');
var combinedArr = arrayA.map(function (v, i) {
return parseInt(v,10) + parseInt(arrayB[i],10); // or return (+v) + (+arrayB[i]);
});
console.log(combinedArr.join(':')); //1:3:8:6

Try this
var a = "1:2:3:4";
var b = "0:1:5:2";
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i in a_arr) {
var to_add = 0;
if (b_arr[i] != undefined) to_add = b_arr[i];
c_arr[i] = a_arr[i] + to_add;
}

You don't need a second loop. The resulting array of the following snippet will have the length of the shorter input array.
var a = '1:2:3:4'
var b = '0:1:5:2'
var aArray = a.split(':')
var bArray = b.split(':')
var result = []
for (
var i = 0, aLength = aArray.length, bLength = bArray.length;
i < aLength && i < bLength;
i++
) {
result.push(Number(a[i]) + Number(b[i]))
}
result = result.join(':')
console.log(result)

Related

How to combine arrays according indexes in javascript?

I have two 2d arrays:
var ar1 = [];
var ar1[0] = [];
var ar1[0][0] = 1;
var ar1[0][1] = 2;
var ar1[1] = [];
var ar1[1][0] = 3;
var ar1[1][1] = 4;
var ar2 = [];
var ar2[0] = [];
var ar2[0][3] = 5;
var ar2[0][4] = 6;
var ar2[1] = [];
var ar2[1][5] = 7;
var ar2[1][6] = 8;
How can I get the combined array that will look like:
var ar1[0][0] = 1;
var ar1[0][1] = 2;
var ar1[1][0] = 3;
var ar1[1][1] = 4;
var ar1[0][3] = 5;
var ar1[0][4] = 6;
var ar1[1][5] = 7;
var ar1[1][6] = 8;
I tried:
ar1.push(ar2);
but this puts whole ar2 to the first empty row of ar1.
One possibility is to forEach over the second array, and Object.assign each subarray onto the appropriate index in the first:
var ar1 = [];
ar1[0] = [];
ar1[0][0] = 1;
ar1[0][1] = 2;
ar1[1] = [];
ar1[1][0] = 3;
ar1[1][1] = 4;
var ar2 = [];
ar2[0] = [];
ar2[0][3] = 5;
ar2[0][4] = 6;
ar2[1] = [];
ar2[1][5] = 7;
ar2[1][6] = 8;
ar2.forEach((subarr2, i) => {
Object.assign(ar1[i], subarr2);
});
console.log(ar1);
Do note that var should only be used when declaring a new variable name for the first time - when assigning to an existing variable, omit it. (Also, sparse arrays are rarely a good idea)
You could iterate the second array and assign all values to the first array. For not given array in the second level take an array as default.
var ar1 = [],
ar2 = [];
ar1[0] = [];
ar1[0][0] = 1;
ar1[0][1] = 2;
ar1[1] = [];
ar1[1][0] = 3;
ar1[1][1] = 4;
ar2[0] = [];
ar2[0][3] = 5;
ar2[0][4] = 6;
ar2[1] = [];
ar2[1][5] = 7;
ar2[1][6] = 8;
ar2.forEach((a, i) => {
ar1[i] = ar1[i] || [];
a.forEach((v, j) => ar1[i][j] = v);
});
console.log(ar1);

How to get characters from second last index using indexof in javaScript?

var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = absoluteURL.lastIndexOf('/');
var result = absoluteURL.substring(n + 1);
//alert(result);
console.log(result);
Here I get the result like 'vikas-kohli' as I am using lastIndexOf.
Now if someone wants to get characters from second last index, or it may be 3rd last index, then how can I get this?
I hope I am able to explain my question well
Insteadof using lastIndexOf('/') use string split('/') method.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var splittedStr = absoluteURL.split('/');
console.log(splittedStr);
Then get the required element from an array.
var res = splittedStr[splittedStr.length-n]; // n: 1,2,3..
cosnole.log(res);
DEMO
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var splittedStr = absoluteURL.split('/');
console.log(splittedStr[splittedStr.length-2]);
Sth like this?
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = 2 //second last
var arr = absoluteURL.split('/')
console.log(arr[arr.length-n])
Just split your URL with /:
var absoluteUrl = "http://stackoverflow.com/users/6262169/vikas-kohli";window.location.pathname;
var splitedUrl = absoluteUrl .split('/');
console.log(splitedUrl);
Then get the element you want in the array.
IndexOf or something like that may not what you need. You can use split instead.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli";
var partNo = 3;
var parts = absoluteURL.split('/');
alert(parts[parts.length - partNo]);
A simple for loop would do the trick.
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n = absoluteURL.indexOf('/');
absoluteURL = absoluteURL.substring(n+2); // Becasue there are two / first
for(i = 0; i < x ; i++) // x should be such that if it is 1, then only the last string will come, if 2, then the last two strings
{
n = absoluteURL.indexOf('/');
absoluteURL = absoluteURL.substring(n+1);
}
You can use .split() on the window.location.pathname:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
arr.forEach(function(item){
console.log(item);
});
With specific indexes:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
console.log('last::::',arr[arr.length-1]);
console.log('second last::::', arr[arr.length-2]);
Or subsequent pop() can give you last item of array:
var locPath = "users/6262169/vikas-kohli"; // window.location.pathname;
var arr = locPath.split('/');
console.log(JSON.stringify(arr, 0, 0), '<---last::::popped-->',arr.pop());
console.log(JSON.stringify(arr, 0, 0), '<-----second last::::popped--->', arr.pop());
We can add a function to do that ourselves.
Add below code snippet:
String.prototype.nIndexOf = function (char, index) {
if (index >= this.split(char).length)
return -1;
else
return this.split(char, index).join(char).length;
}
Then you can use this as following:
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var n1 = absoluteURL.nIndexOf('/', 4);
var n2 = absoluteURL.nIndexOf('/', 5);
var result = absoluteURL.substring(n1 + 1, n2);
alert(result);
Hi if u can get nth Index from user u can use this
var nthIndex = 2;
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
for (i = 0; i < nthIndex; i++) {
var n = absoluteURL.lastIndexOf('/');
absoluteURL = absoluteURL.substring(0,n);}
alert(absoluteURL);
Concatenate string from the index you want after splitting it with /
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli";
var n = 2; // set the index from where you want to get characters
var arr = absoluteURL.split('/');
var a = [];
for(var i=n,j=0; i>=0; i--,j++){
a[j] = arr[arr.length-i];
}
console.log(a.join('')); // you can join it with any character
This should work:
var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"
var results = absoluteURL.split('/');
var result = results[results.length-2];
alert(result);

How to prevent rewrite data in array while looping

What I like is an Array like this
myArray = [
[{"value":1},{"value":2},{"value":3}]
[{"value":2},{"value":4},{"value":6}]
]
I try to use two loops to build it. The outer loop shout build the two "outer" Elements in Array, the inner loop shout build the 3 inner objects.
http://jsfiddle.net/xtrem1234/xx06zt5s/
var dataset = [];
var categories = ["Category_1", "Category_2"];
var myArray = [];
categories.forEach(function (category, index) {
for (var n = 1; n < 4; n++) {
var d;
d = {};
d.value = (index+1) * n;
console.log("index: " + index);
console.log("n: " + n);
console.log("d.value: " + d.value);
dataset[n] = d;
}
myArray.push(dataset);
});
console.log(JSON.stringify(myArray));
The issue is, your array dataset is a global array. Define it inside forEach loop.
Code
var categories = ["Category_1", "Category_2"];
var myArray = [];
categories.forEach(function(category, index) {
var dataset = [];
for (var n = 1; n < 4; n++) {
var d;
d = {};
d.value = (index + 1) * n;
dataset[n] = d;
}
myArray.push(dataset);
});
console.log(JSON.stringify(myArray));
A: you need to reinitialize the dataset array each time the forEach loop runs
B: you can just push() the info to the dataset array, the same way you do for myArray
var categories = ["Category_1", "Category_2"];
var myArray = [];
categories.forEach(function (category, index) {
var dataset = [];
for (var n = 1; n < 4; n++) {
dataset.push({'value': (index+1) * n});
}
myArray.push(dataset);
});
console.log(JSON.stringify(myArray));

JavaScript object dimensions

I want to define a two-dimensional object, but I do not succeed.
var b = [1,2,3,4,5,6,7,8];
var a = {};
var c = ["baslik","resim","icerik","links"];
for(i=0;i<2;i++){
for(s=0;s<4;s++){
a[c[s]]=b[s];
}
}
document.writeln(JSON.stringify(a));
Output:
{"baslik":1,"resim":2,"icerik":3,"links":4}
I want this output:
{"baslik":1,"resim":2,"icerik":3,"links":4},
{"baslik":5,"resim":6,"icerik":7,"links":8}
Try:
var a = []; //Must be a array
var b = [1,2,3,4,5,6,7,8];
var c = ["baslik","resim","icerik","links"];
for(i=0;i<2;i++){
var obj = {} //Object
for(s=0;s<4;s++){
obj[c[s]]=b[s+4*i];
}
a.push(obj)
}
document.writeln(JSON.stringify(a));
Try like this
var b = [1,2,3,4,5,6,7,8];
var a = [];
var c = ["baslik","resim","icerik","links"];
var n= Math.floor(b.length/c.length);
var k=0;
for(var i=0;i<n;i++){
var entity={};
for(var j=0;j<c.length;j++){
entity[c[j]]= k<b.length ? b[k++] : 0;
}
a.push(entity);
}
console.log(JSON.stringify(a));
Try:
var b = [1, 2, 3, 4, 5, 6, 7, 8];
var a = [];
var c = ["baslik", "resim", "icerik", "links"];
var n = c.length;
b.reduce(function(x, num, i) {
x[c[i % n]] = num;
if (((i + 1) % n) == 0) {
a.push(x);
x = {};
}
if ((i + 1) == b.length) return a;
return x;
}, {})
console.log(JSON.stringify(a));

Change Array Formatting

How to change this Javascript array format:
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
to this object format:
var sample_data = {"af":"16.63","al":"11.58","dz":"158.97"};
Could use Array.shift to do it too. No idea how it compares to other methods speed wise.
var sample_data = ["af","16.63","al","11.58","dz","158.97"]; // source
var data = sample_data.slice(); // clone the data
sample_data = {};
while (data.length > 1) {
sample_data[data.shift()] = data.shift() || null;
}
var d = {}; // a temporary object
for (var i = 0; i < sample_data.length; i += 2) {
// iterate over sample_data with a step width of 2
// and set the the data in the temp. object
d[sample_data[i]] = sample_data[i+1];
}
sample_data = d;
the code for it will look like this
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
var tmp = sample_data;
sample_data = {};
for (var i = 0; i < tmp.length / 2; i++)
sample_data[tmp[i * 2]] = tmp[i * 2 + 1];
EDIT
Keep in mind.
var arr = []; // This is an array
var obj = {}; // This is an object! Not array.

Categories