I've got couple arrays I want to horizontally merge:
data1 = [["ID"], [21], [26], [32]]
data2 = [["A", "B", "C"],[10, 10, 10], [95, 95, 95], [95, 95, 95]]
Both array always have the same number of "rows"
I'm looking for this result:
result = [["ID", "A" , "B", "C"],[21, 10, 10, 10]...]
Currently I have the following code:
for ( var i = 0; i < data1.length; i++ ) {
data3.push( [ data1[i], data2[i] ] );
}
Which is giving me a strange result and I don't really understand why.
[[["A"], [10, 10 ,10]]]
Any help? I always struggle with Arrays.
That is not a weird result.
To achieve what you need, please try this
data3.push( data2[i].unshift(data1[i][0]) );
Assumption: A, B, C are Strings, like 'A'
Suggestion: You should follow a better datastructure. but still try the below solution. Array index starts from 1. You kept on changing the question, and I need to update my answer accordingly. I tried the below, it works for me.
var data1 = [["ID"], [21], [26], [32]];
var data2 = [["A", "B", "C"],[10, 10, 10], [95, 95, 95], [95, 95, 95]];
var data3 = [];
for ( var i = 0; i < data1.length; i++ ) {
data2[i].unshift(data1[i][0]);
data3.push(data2[i] );
}
console.log(data3)
Gives me the following output
[["ID","A","B","C"], [21, 10, 10, 10], [26, 95, 95, 95] ,[32, 95, 95, 95]]
Related
Presently I have a multidimensional array that I want to loop over. All I want is to push the inner elements to an empty array. But What I'm getting is totally different from the expected output.
All have done so far below
const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ];
function addItemToCart() {
let new_items = [] // I want this array to be [2, 7, 12, 17, 22, 27]
// looping outer array elements
for(let i = 0; i < prices.length; i++) {
for(let j = 0; j < prices[i].length; j++) {
new_items.push(prices[i][j])
console.log(new_items);
}
}
}
addItemToCart()
Use map: const newItems = prices.map(price => price[0])
Do you want to completely flatten your array, or just take the first item from each inner array and copy that to the new array?
If you want to flatten it completely, you can do it like this:
const newArray = prices.reduce((res, arr) => [...res, ...arr], []);
If you only want the first item from each inner array, I would recommend the solution that Konstantin suggested.
You don't need loops for that:
const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ];
const toAdd = [].concat.apply([], prices);
console.log(toAdd);
Here is my code;
var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var averageData = [];
data.forEach(function(entries) {
entries.reduce(function(a, b) {
return a + b[1];
}, 0);
console.log(entries);
});
I would like to be able to add the numbers from each array together.
But I'm not sure how I can get each array of numbers added together from the forEach loop?
From this data I would like to output instead [120, 60, 165].
It is important that the data is within a nested array, the aim is to try get it out of the nested array onto a single line with the above output.
Hope someone can offer some advice!
Thanks
Use Array#map instead
Note that b[1] holds nothing(undefined) and entries.reduce returns a reduced value, either return it of keep it in variable
var data = [
[40, 20, 60],
[20, 30, 10],
[50, 75, 40]
];
var averageData = data.map(function(entries) {
return entries.reduce(function(a, b) {
return a + b;
}, 0);
});
console.log(averageData)
Edit-
As suggested in comments by #Tushar, ES6 version
var data = [
[40, 20, 60],
[20, 30, 10],
[50, 75, 40]
];
console.log(data.map(arr => arr.reduce((a, b) => a + b, 0)));
reduce() will return the sum as you want at last. See as below.
var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var averageData = []
data.forEach(function(entries) {
var sum = entries.reduce(function(a, b) {
return a + b;
}, 0)
console.log(sum)
})
If your values are safe (meaning you know where there come from) you could use eval to quickly sum the values.
var data = [[40, 20, 60], [20, 30, 10], [50, 75, 40]];
var totals = [];
data.forEach(function(a, i) {
totals.push(eval(a.join('+')));
});
console.log(totals);
Not the most efficient way but it works
Below is the structure of my data;
{
"questions": ["Large choice of food", "Food quality", "Food freshness"],
"countries": ["Netherlands", "Belgium", "France"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
],
[
[7, 46, 92],
[54, 94, 31],
[89, 96, 11]
]
]
}
Here is my script for sorting it;
function calculateTotals() {
var countryS = "France"
var country = data.countries.indexOf(countryS);
var values
for (var question= 0; question < data.questions.length; question++) {
// get the values for the question/country
values = data.values[question][country];
console.log(values)
Currently, this outputs this to the console;
So, currently this script is logging the values for each question indexed by country.
I would like to add together each item in this array. So, from this output I would like to do the following additions;
29 + 49 + 89,
78 + 86 + 96,
80 + 43 + 11
I'm not sure how I can do this?
I thought that perhaps using .pop()/.shift() 3 times might work, or just using [0],[1],[2]. However, after returning a single item in the array, I'm not sure how to add the 3 arrays numbers together?
Hope everything is clear, any help/advice is much appreciate!
Plunk Here
You could use an array for the sum amd iterate over the items as well.
Basically this proposal uses Array#forEach.
The forEach() method executes a provided function once per array element.
function calculateTotals() {
var countryS = "France",
country = data.countries.indexOf(countryS),
sum = [];
data.values.forEach(function (question) {
question[country].forEach(function (a, i) {
sum[i] = (sum[i] || 0) + a;
});
});
console.log(sum);
}
var data = { "questions": ["Large choice of food", "Food quality", "Food freshness"], "countries": ["Netherlands", "Belgium", "France"], "values": [[[5, 88, 18], [50, 83, 10], [29, 78, 80]], [[46, 51, 61], [95, 21, 15], [49, 86, 43]], [[7, 46, 92], [54, 94, 31], [89, 96, 11]]] };
calculateTotals();
You can use array map function to iterate over them and perform such an operation.
E.g.
var arr = [[29,49,89], [78,86,96], [80,43,11]];
var final = arr.map(function(v){
var res = 0;
v.forEach(function(e){
res += e;
});
return res;
});
console.log(final); //[167, 260, 134]
For simpler, but not recommended, you can also achieve it by doing,
var arr = [[29,49,89], [78,86,96], [80,43,11]];
var final = arr.map(function(v){
return eval(v.join('+'));
});
console.log(final); //[167, 260, 134]
try the updated plunkr
Here is the updated method
function calculateTotals()
{
var countryS = "France"
var country = data.countries.indexOf(countryS);
var sum = [0,0,0];
for (var question= 0; question < data.questions.length; question++)
{
var values = data.values[question][country];
for( var counter = 0; counter < values.length; counter++ )
{
sum[counter] += values[counter];
}
}
document.body.innerHTML += sum;
}
DEMO
var data = {
"questions": ["Large choice of food", "Food quality", "Food freshness"],
"countries": ["Netherlands", "Belgium", "France"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
],
[
[7, 46, 92],
[54, 94, 31],
[89, 96, 11]
]
]
}
function calculateTotals() {
var countryS = "France"
var country = data.countries.indexOf(countryS);
var sum = [0, 0, 0];
for (var question = 0; question < data.questions.length; question++) {
var values = data.values[question][country];
for (var counter = 0; counter < values.length; counter++) {
sum[counter] += values[counter];
}
}
document.body.innerHTML += sum;
}
calculateTotals();
You can use array.reduce to achieve the desired output.
for (var question= 0; question < data.questions.length; question++) {
// get the values for the organization/country
values = data.values[question][country];
console.log(values);
var sumOfValues = values.reduce(
function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
console.log("Sum of values");
console.log(sumOfValues);
}
here's the plunkr
https://plnkr.co//TckVhx52VcMGgb0eZjzW?p=preview
EDIT:
array.reduce is one of the fastest methods available. Many links can be found for the info.
I've got one here. See the answers.
How to find the sum of an array of numbers
Try the following with pure JavaScript with nested loops::
(If you want to get all the additions)
var arr = [[29,49,89], [78,86,96], [80,43,11]];
var resultArr;
for(var i = 0, len = arr.length; i < len; i++) {
for(var j = 0, len2 = arr.length; j < len2; j++) {
resultArr+= arr[j][i];
}
}
If you only want to get one sum at a time:
var result;
for(var i = 0, len = arr.length; i < len; i++) {
result+= arr[j]["YourIndex"];
}
i have a problem with adding new values to existing objects when they have equal values. My point is to add new value to existing object, but when object value is equal with other postion object value then they have to get same new value, but otherwise object get just a value.
var array = [
{"first": [10, 20], "last": [40, 50]},
{"first": [60, 22], "last": [10, 20]},
{"first": [40, 50], "last": [60, 22]},
{"first": [40, 50], "last": [44, 33]}
];
for (var i = 0; i < (array.length); i++) {
for (var j = 0; j < (array.length); j++) {
if (array[i].first[0] == array[j].last[0] && array[i].first[1] == array[j].last[1]) {
/* I'm not sure, what to do here
but I want to add same values to equal objects
*/
array[i].first.push(i);
array[j].first.push(i);
}
}
}
I want to get that output:
var array = [
{"first": [10, 20, 1], "last": [40, 50, 2]},
{"first": [60, 22, 3], "last": [10, 20, 1]},
{"first": [40, 50, 2], "last": [60, 22, 3]},
{"first": [40, 50, 2], "last": [44, 33, 4]}
];
last number are new values,but im not sure how do get that output, i think maybe one way is to save equal objects positions and then doing something with them , but im not sure, maybe can somebody give me advice?
As in comments to Your question, I also find this problem quite strange. But... I think this is what You seek:
<script>
var array = [
{"first": [10, 20], "last": [40, 50]},
{"first": [60, 22], "last": [10, 20]},
{"first": [40, 50], "last": [60, 22]},
{"first": [40, 50], "last": [44, 33]}
];
// This variable will hold unique subarrays.
// Index of it will be the number added to each subarray.
var matches = new Array();
var check_it = function(matches,subarr)
{
// Finding index of subarray in matches
var index = matches.map( /./.test, RegExp( "^"+subarr+"$" )).indexOf(true);
// If this subarray is new
if(index === -1)
{
// Add copy of it to matches
matches.push([subarr[0],subarr[1]]);
// Assing index to it
subarr.push(matches.length-1);
}
// If this subarray exist in matches
else
{
// Add the index of first match to it
subarr.push(index);
}
}
for (var i = 0; i < (array.length); i++) {
// For each subarray do the checking.
check_it(matches,array[i].first);
check_it(matches,array[i].last);
}
console.log(array);
</script>
From here I get code to find index of array in array.
I have an array of arrays in javascript set up within an object that I'm storing with local storage. It's high scores for a Phonegap game in the format {'0':[[score,time],[score,time]} where 0 is the category. I'm able to see the scores using a[1][0]. I want to sort with the high scores first.
var c={'0':[[100,11],[150,12]};
c.sort(function(){
x=a[0];
y=b[0];
return y-x;
}
However, b[0] always gives an undefined error.
I'm new to Javascript and making this is my first major test as a learning experience. Though I've looked at a number of examples on stackoverflow still can't figured this one out.
You need to declare the parameters to the comparator function.
c.sort(function(){
should be
c.sort(function(a, b){
and you need to call sort on an array as "am not i am" points out so
var c={'0':[[100,11],[150,12]]};
c[0].sort(function(a, b){
var x=a[0];
var y=b[0];
return y-x;
});
leaves c in the following state:
{
"0": [
[150, 12],
[100, 11]
]
}
function largestOfFour(arr) {
for(var x = 0; x < arr.length; x++){
arr[x] = arr[x].sort(function(a,b){
return b - a;
});
}
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
var myArray = [ [11, 5, 6, 3, 10], [22,55,33,66,11,00], [32, 35, 37, 39], [1000, 1001, 1002, 1003, 999]];
_.eachRight(myArray, function(value) {
var descending = _.sortBy(value).reverse();
console.log(descending);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>