need some help with a script completely on array that I'm doing
skill = [
//[ID, "NAME", TMLEVEL, Learn, Mastery, Prerequisite, PrerequisiteLvl],
//Schoolgirl, Fighter
[0, "Steel Punch", 0, 0, null, null],
[1, "Shockwave", 1, 1, 2, null],
[2, "Bull's Eye", 10, 2, 2, null],
[3, "Burning Rave", 20, 2, 2, null],
[4, "Shockvibe", 20, 1, 2, null],
[5, "Sense Breaker", 20, 1, 2, null],
[6, "Luck Breaker", 20, 1, 2, null],
[7, "Pumping Heart", 25, 3, 3, skill[3], 1],
[8, "Armor Breaker", 30, 2, 2, skill[1], 10],
[9, "Upper Smash", 40, 2, 2, skill[2], 10],
[10, "Hyper Beat", 45, 4, 3, [skill[2],skill[3]], [10,10]],
[11, "Tornado Bomb", 50, 3, 3, skill[8], 1]
];
I need that inside the array, in certain points, to call th array again to put the array value in there, like i have here.
In theory this works fine, without any error, but when i call the array inside it,it says that it's "undefined".
Any one knows how can i do this without rewrite everything on it? (because i use this in +- 300 code lines).
After a long process, I have come up with a solution that will replace all prerequisites, even if they are several levels deep (e.g. skill_3 requires skill_2 which requires skill_1...).
This will require your skill variable to be correctly declared (in your question, not all of the skills had 7 variables).
Here is an example of what the variable will look like:
var skill = [
//[ID, "NAME", TMLEVEL, Learn, Mastery, Prerequisite, PrerequisiteLvl],
[0, "Steel Punch", 0, 0, 0, null, null],
[1, "Shockwave", 1, 1, 2, null, null],
[2, "Bull's Eye", 10, 2, 2, 7, null],
[3, "Burning Rave", 20, 2, 2, null, null],
[4, "Shockvibe", 20, 1, 2, null, null],
[5, "Sense Breaker",20, 1, 2, null, null],
[6, "Luck Breaker", 20, 1, 2, null, null],
[7, "Pumping Heart",25, 3, 3, 3, 1],
[8, "Armor Breaker",30, 2, 2, 7, 10],
[9, "Upper Smash", 40, 2, 2, 2, 10],
[10,"Hyper Beat", 45, 4, 3, [2,3], [10,10]],
[11,"Tornado Bomb", 50, 3, 3, 8, 1]
];
Now, I thought of a function setPrerequisites() that will, for 1 skill, recursively set it's prerequisites:
Array.prototype.setPrerequisites = function(){
if (typeof this[5] === "number")
{
this[5]=skill[getPosOfSkill(this[5])];
this[5].setPrerequisites();
}
else if (this[5] instanceof Array)
{
if (this[5].isSkill()) this[5].setPrerequisites();
else
{
for(var i = 0; i < this[5].length; i++)
{
this[5][i] = skill[getPosOfSkill(this[5][i])];
this[5][i].setPrerequisites();
}
}
}
}
This function uses isSkill() to determine whether an array is a skill, or an array of skill IDs:
Array.prototype.isSkill = function(){
return this.length==7 && typeof this[1]==="string";
}
It also uses getPosOfSkill(id) to look for the right skill in case your skills were listed in no particular order, or if ID's are missing:
function getPosOfSkill(id){
for(var i=0; i<skill.length; i++) if (skill[i][0]==id) return i;
return false;
}
All you have to do is declare your skill variable, and then fill it:
for (var i = 0; i < skill.length; i++) skill[i].setPrerequisites();
// if you want to see the results
console.log(skill);
Here is a jsFiddle Demo
You'll have to either rethink your whole approach here (recommended), or set those items to null at first, then rerun the declaration:
skill = [
//[ID, "NAME", TMLEVEL, Learn, Mastery, Prerequisite, PrerequisiteLvl],
//Schoolgirl, Fighter
[0, "Steel Punch", 0, 0, null, null],
[1, "Shockwave", 1, 1, 2, null],
[2, "Bull's Eye", 10, 2, 2, null],
[3, "Burning Rave", 20, 2, 2, null],
[4, "Shockvibe", 20, 1, 2, null],
[5, "Sense Breaker", 20, 1, 2, null],
[6, "Luck Breaker", 20, 1, 2, null],
[7, "Pumping Heart", 25, 3, 3, null, 1],
[8, "Armor Breaker", 30, 2, 2, null, 10],
[9, "Upper Smash", 40, 2, 2, null, 10],
[10, "Hyper Beat", 45, 4, 3, null, null],
[11, "Tornado Bomb", 50, 3, 3, null, 1]
];
skill = [
//[ID, "NAME", TMLEVEL, Learn, Mastery, Prerequisite, PrerequisiteLvl],
//Schoolgirl, Fighter
[0, "Steel Punch", 0, 0, null, null],
[1, "Shockwave", 1, 1, 2, null],
[2, "Bull's Eye", 10, 2, 2, null],
[3, "Burning Rave", 20, 2, 2, null],
[4, "Shockvibe", 20, 1, 2, null],
[5, "Sense Breaker", 20, 1, 2, null],
[6, "Luck Breaker", 20, 1, 2, null],
[7, "Pumping Heart", 25, 3, 3, skill[3], 1],
[8, "Armor Breaker", 30, 2, 2, skill[1], 10],
[9, "Upper Smash", 40, 2, 2, skill[2], 10],
[10, "Hyper Beat", 45, 4, 3, [skill[2],skill[3]], [10,10]],
[11, "Tornado Bomb", 50, 3, 3, skill[8], 1]
];
That way, the array elements you are trying to access already exist, now you are just overwriting them.
I think i found a easy way, but still has the problem if it's defined after, but since i only call the values defined before there is no problem for now.
But if anyone knows some way better let me know please.
Here is what i do still using only arrays:
var skill = [];
skill[0] = [0, "Steel Punch", 0, 0, null, null];
skill[1] = [1, "Shockwave", 1, 1, 2, null];
skill[2] = [2, "Bull's Eye", 10, 2, 2, null];
skill[3] = [3, "Burning Rave", 20, 2, 2, null];
skill[4] = [4, "Shockvibe", 20, 1, 2, null];
skill[5] = [5, "Sense Breaker", 20, 1, 2, null];
skill[6] = [6, "Luck Breaker", 20, 1, 2, null];
skill[7] = [7, "Pumping Heart", 25, 3, 3, skill[3], 1];
skill[8] = [8, "Armor Breaker", 30, 2, 2, skill[1], 10];
skill[9] = [9, "Upper Smash", 40, 2, 2, skill[2], 10];
skill[10] = [10, "Hyper Beat", 45, 4, 3, [skill[2],skill[3]], [10,10]];
skill[11] = [11, "Tornado Bomb", 50, 3, 3, skill[8], 1];
This way i define them and i'm still using the arrays has i wanted (1 night of sleep makes me think much better :P)
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I need this for a codewars challenge to make my code DRY
I have an array of arrays, lets say a 9x9 matrix.
const sudokuTest2= [
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 0, 3, 4, 9],
[1, 0, 0, 3, 4, 2, 5, 6, 0],
[8, 5, 9, 7, 6, 1, 0, 2, 0],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 0, 1, 5, 3, 7, 2, 1, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 0, 0, 4, 8, 1, 1, 7, 9],
];
How can I divide it automatically into 9 equal areas, something which results from the following sample code:
const areas = [];
areas[0] = sudokuTest2[0]
.slice(0, 3)
.concat(sudokuTest2[1].slice(0, 3))
.concat(sudokuTest2[2].slice(0, 3));
areas[1] = sudokuTest2[3]
.slice(0, 3)
.concat(sudokuTest2[4].slice(0, 3))
.concat(sudokuTest2[5].slice(0, 3));
areas[2] = sudokuTest2[6]
.slice(0, 3)
.concat(sudokuTest2[7].slice(0, 3))
.concat(sudokuTest2[8].slice(0, 3));
areas[3] = sudokuTest2[0]
.slice(3, 6)
.concat(sudokuTest2[1].slice(3, 6))
.concat(sudokuTest2[2].slice(3, 6));
areas[4] = sudokuTest2[3]
.slice(3, 6)
.concat(sudokuTest2[4].slice(3, 6))
.concat(sudokuTest2[5].slice(3, 6));
areas[5] = sudokuTest2[6]
.slice(3, 6)
.concat(sudokuTest2[7].slice(3, 6))
.concat(sudokuTest2[8].slice(3, 6));
areas[6] = sudokuTest2[0]
.slice(6, 9)
.concat(sudokuTest2[1].slice(6, 9))
.concat(sudokuTest2[2].slice(6, 9));
areas[7] = sudokuTest2[3]
.slice(6, 9)
.concat(sudokuTest2[4].slice(6, 9))
.concat(sudokuTest2[5].slice(6, 9));
areas[8] = sudokuTest2[6]
.slice(6, 9)
.concat(sudokuTest2[7].slice(6, 9))
.concat(sudokuTest2[8].slice(6, 9));
For sure I could use some nested loops, but I'm curious if there is any solution with array methods.
What will be the best solution, what do you think?
You could take generate the wanted 3x3 parts by using a nested mapping.
const
sudoku = [[5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 0, 3, 4, 9], [1, 0, 0, 3, 4, 2, 5, 6, 0], [8, 5, 9, 7, 6, 1, 0, 2, 0], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 0, 1, 5, 3, 7, 2, 1, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 0, 0, 4, 8, 1, 1, 7, 9]],
areas = Array
.from({ length: 3 })
.flatMap((_, i) => Array
.from(
{ length: 3 },
(__, j) => Array
.from({ length: 3 })
.flatMap((___, k) => sudoku[j * 3 + k].slice(i * 3, (i + 1) * 3)
)
));
areas.forEach(a => console.log(...a));
This can be done in with single forEach method. The idea behind this is dynamic indexing.
const matrix = [ [5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 0, 3, 4, 9], [1, 0, 0, 3, 4, 2, 5, 6, 0], [8, 5, 9, 7, 6, 1, 0, 2, 0], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 0, 1, 5, 3, 7, 2, 1, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 0, 0, 4, 8, 1, 1, 7, 9],];
let areas = new Array(9).fill([]);
matrix.forEach((numbers, idx)=> {
let segment = Math.floor(idx / 3);
areas[segment] = [...areas[segment], ...matrix[idx].slice(0, 3)];
areas[segment + 3] = [...areas[segment + 3], ...matrix[idx].slice(3, 6)];
areas[segment + 6] = [...areas[segment + 6], ...matrix[idx].slice(6, 9)];
})
areas.forEach(area => console.log(...area));
We have an array of arrays like this:
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
There may be duplicate elements in each array and that's fine.
But I'm after a proper solution to remove duplicate elements in each set comparing to lower sets!
So as we have a 0 in the first array and the last array, we should consider the 0 in last one a duplication and remove it...
the desired result would be:
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[12],
[14]
It's a confusing issue for me please help...
You could collect the values in an object with index as value, and filter for values who are at the same index.
const
arrays = [[0, 1, 2, 3, 4, 4, 4, 4], [5, 6, 7, 8, 9, 10, 11, 11], [2, 7, 10, 12], [0, 7, 10, 14]],
seen = {},
result = arrays.map((array, i) => array.filter(v => (seen[v] ??= i) === i));
result.forEach(a => console.log(...a));
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[4, 4, 5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
]
let filtered = arrays.map((row, i) => {
// concat all previous arrays
let prev = [].concat(...arrays.slice(0, i))
// filter out duplicates from prev arrays
return row.filter(r => !prev.includes(r))
})
console.log(filtered)
We can do this using Array#reduce and maintain a seen Set, which will have all visited numbers from each array.
Once you iterate over an array you push all visited elements in the seen Set, then push a new array filtered by the elements not in the seen Set:
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
const removeDupsInSibling = (arr) => {
let seen = new Set();
return arr.reduce((acc, a)=> {
const f = a.filter(v => !seen.has(v));
seen = new Set([...seen, ...a]);
acc.push(f);
return acc;
}, []);
}
console.log(removeDupsInSibling(arrays));
There are plenty of inefficient ways to do this, but if you want to do this in O(n), then we can make the observation that what we want to know is "which array a number is in". If we know that, we can run our algorithm in O(n):
for every element e in array at index i:
if index(e) == i:
this is fine
if index(e) < i:
remove this e
So let's just do literally that: we allocate an object to act as our lookup, and then we run through all elements:
const lookup = {};
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
const reduced = arrays.map((array, index) => {
// run through the elements in reverse, so that we can
// safely remove bad elements without affecting the loop:
for(let i=array.length-1; i>=0; i--) {
let value = array[i];
let knownIndex = (lookup[value] ??= index);
if (knownIndex < index) {
// removing from "somewhere" in the array
// uses the splice function:
array.splice(i,1);
}
}
return array;
});
console.log(reduced);
For an alternative, where the loop+splice is taken care of using filter, see Nina's answer.
Simple, clean and high performance solution:
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14]
];
const duplicates = {};
const answer = arrays.map( (array, level) => {
return array.filter( el => {
if ( duplicates[el] < level ) {
// return nothing; fine
} else {
duplicates[el] = level;
return el
}
})
});
console.log(JSON.stringify(answer))
here is on-liner and less-readable form:
const d = {}, arrays = [ [0, 1, 2, 3, 4, 4, 4, 4], [5, 6, 7, 8, 9, 10, 11, 11], [2, 7, 10, 12], [0, 7, 10, 14]];
const answer = arrays.map((a,l)=> a.filter(el=> d[el]<l ? 0 : (d[el]=l,el)));
console.log(JSON.stringify(answer))
const arrays = [
[0, 1, 2, 3, 4, 4, 4, 4],
[5, 6, 7, 8, 9, 10, 11, 11],
[2, 7, 10, 12],
[0, 7, 10, 14],
];
const output = arrays.reduce(
({ output, set }, current, i) => {
output[i] = current.filter((num) => !set.has(num));
[...new Set(output[i])].forEach((num) => set.add(num));
return { output, set };
},
{ output: [], set: new Set() }
).output;
console.log(output);
Gets the exact output you want:
[
[
0, 1, 2, 3,
4, 4, 4, 4
],
[
5, 6, 7, 8,
9, 10, 11, 11
],
[ 12 ],
[ 14 ]
]
Create a function that accepts a string and groups repeated values. The groups should have the following structure: [[value, first_index, last_index, times_repeated], ..., [value, first_index, last_index, times_repeated]].
value: Character being assessed.
first_index: Index of characters first appearance.
last_index: Index of characters last appearance.
times_repeated: Number of consecutive times character repeats.
Examples
findRepeating("a") ➞ [["a", 0, 0, 1]]
findRepeating("aabbb") ➞ [["a", 0, 1, 2], ["b", 2, 4, 3]]
findRepeating("1337") ➞ [["1", 0, 0, 1], ["3", 1, 2, 2], ["7", 3, 3, 1]]
findRepeating("aabbbaabbb") ➞ [["a", 0, 1, 2], ["b", 2, 4, 3], ["a", 5, 6, 2], ["b", 7, 9, 3]]
I am able to do it for unique characters.
But unable to do it for
Number of consecutive times character repeats
MY CODE
function findRepeating(str) {
let unique = [...new Set([...str])]
return unique.map(x=>[x,str.indexOf(x),str.lastIndexOf(x),[...str].filter(a=>a==x).length])
}
EXPECTED RESULT
Test.assertSimilar(findRepeating(''), [])
Test.assertSimilar(findRepeating('a'), [['a', 0, 0, 1]])
Test.assertSimilar(findRepeating('1337'), [['1', 0, 0, 1], ['3', 1, 2, 2], ['7', 3, 3, 1]])
Test.assertSimilar(findRepeating('aabbb'), [['a', 0, 1, 2], ['b', 2, 4, 3]])
Test.assertSimilar(findRepeating('addressee'), [['a', 0, 0, 1], ['d', 1, 2, 2], ['r', 3, 3, 1], ['e', 4, 4, 1], ['s', 5, 6, 2], ['e', 7, 8, 2]])
Test.assertSimilar(findRepeating('aabbbaabbb'), [['a', 0, 1, 2], ['b', 2, 4, 3], ['a', 5, 6, 2], ['b', 7, 9, 3]])
Test.assertSimilar(findRepeating('1111222233334444'), [['1', 0, 3, 4], ['2', 4, 7, 4], ['3', 8, 11, 4], ['4', 12, 15, 4]])
Test.assertSimilar(findRepeating('1000000000000066600000000000001'), [['1', 0, 0, 1], ['0', 1, 13, 13], ['6', 14, 16, 3], ['0', 17, 29, 13], ['1', 30, 30, 1]])
ACTUAL RESULT
Test Passed: Value == '[]'
Test Passed: Value == "[['a', 0, 0, 1]]"
Test Passed: Value == "[['1', 0, 0, 1], ['3', 1, 2, 2], ['7', 3, 3, 1]]"
Test Passed: Value == "[['a', 0, 1, 2], ['b', 2, 4, 3]]"
FAILED: Expected: "[['a', 0, 0, 1], ['d', 1, 2, 2], ['r', 3, 3, 1], ['e', 4, 4, 1], ['s', 5, 6, 2], ['e', 7, 8, 2]]", instead got: "[['a', 0, 0, 1], ['d', 1, 2, 2], ['r', 3, 3, 1], ['e', 4, 8, 3], ['s', 5, 6, 2]]"
FAILED: Expected: "[['a', 0, 1, 2], ['b', 2, 4, 3], ['a', 5, 6, 2], ['b', 7, 9, 3]]", instead got: "[['a', 0, 6, 4], ['b', 2, 9, 6]]"
Test Passed: Value == "[['1', 0, 3, 4], ['2', 4, 7, 4], ['3', 8, 11, 4], ['4', 12, 15, 4]]"
FAILED: Expected: "[['1', 0, 0, 1], ['0', 1, 13, 13], ['6', 14, 16, 3], ['0', 17, 29, 13], ['1', 30, 30, 1]]", instead got: "[['1', 0, 30, 2], ['0', 1, 29, 26], ['6', 14, 16, 3]]"
function findRepeating(str) {
let unique = [...new Set([...str])]
return unique.map(x=>[x,str.indexOf(x),str.lastIndexOf(x),[...str].filter(a=>a==x).length])
}
console.log("Fails ",JSON.stringify(findRepeating('addressee')),"\nexpected", `[['a',0,0,1],['d',1,2,2],['r',3,3,1],['e',4,4,1],['s',5,6,2],['e',7,8,2]]`)
console.log("Fails ",JSON.stringify(findRepeating('aabbbaabbb')),"\nexpected", `[['a',0,1,2],['b',2,4,3],['a',5,6,2],['b',7,9,3]]`)
console.log("Passes ",JSON.stringify(findRepeating('1111222233334444')),"\nexpected", `[['1',0,3,4],['2',4,7,4],['3',8,11,4],['4',12,15,4]]`)
console.log("Fails ",JSON.stringify(findRepeating('1000000000000066600000000000001')),"\nexpected", `[['1',0,0,1],['0',1,13,13],['6', 14,16,3],['0',17,29,13],['1',30,30,1]]`)
You could take an array of same characters with a regular expression which looks for a character and same following onces as a group and map the wanted information.
function findRepeating(string) {
var i = -1;
return (string.match(/(.)\1*/g) || []).map(s => [s[0], ++i, i += s.length - 1, s.length]);
}
console.log(findRepeating("")); // []
console.log(findRepeating("a")); // [["a", 0, 0, 1]]
console.log(findRepeating("aabbb")); // [["a", 0, 1, 2], ["b", 2, 4, 3]]
console.log(findRepeating("1337")); // [["1", 0, 0, 1], ["3", 1, 2, 2], ["7", 3, 3, 1]]
console.log(findRepeating("aabbbaabbb")); // [["a", 0, 1, 2], ["b", 2, 4, 3], ["a", 5, 6, 2], ["b", 7, 9, 3]]
Your code assumes that each group is about a different character. As soon as you have two groups with the same character, things like lastIndex will give the wrong result.
Just use a plain for-loop.
function findRepeating(str) {
let result = [];
let start = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] !== str[i+1]) {
result.push([str[i], start, i, i-start+1]);
start = i+1;
}
}
return result;
}
console.log(findRepeating(''), [])
console.log(findRepeating('a'), [['a', 0, 0, 1]])
console.log(findRepeating('1337'), [['1', 0, 0, 1], ['3', 1, 2, 2], ['7', 3, 3, 1]])
console.log(findRepeating('aabbb'), [['a', 0, 1, 2], ['b', 2, 4, 3]])
console.log(findRepeating('addressee'), [['a', 0, 0, 1], ['d', 1, 2, 2], ['r', 3, 3, 1], ['e', 4, 4, 1], ['s', 5, 6, 2], ['e', 7, 8, 2]])
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to change the heatmap series data using setData() when the dropdown value is changed. Please check my working jsfiddle
When clicking on the second option from the dropdown then heatmap should redraw() with new series data.
You have wrong data format in setData method, you have a few arrays - it should be one array , similar to data in series:
chart.series[0].setData([
[0, 0, 16],
[0, 1, 14],
[0, 2, 38],
[0, 3, 24],
[0, 4, 67],
[1, 0, 92],
[1, 1, 58],
[1, 2, 78],
[1, 3, 117],
[1, 4, 48],
[2, 0, 35],
[2, 1, 15],
[2, 2, 123],
[2, 3, 64],
[2, 4, 52],
[3, 0, 72],
[3, 1, 132],
[3, 2, 114],
[3, 3, 19],
[3, 4, 16],
[4, 0, 38],
[4, 1, 5],
[4, 2, 8],
[4, 3, 117],
[4, 4, 115],
[5, 0, 88],
[5, 1, 32],
[5, 2, 12],
[5, 3, 6],
[5, 4, 120],
[6, 0, 13],
[6, 1, 44],
[6, 2, 88],
[6, 3, 98],
[6, 4, 96],
[7, 0, 31],
[7, 1, 1],
[7, 2, 82],
[7, 3, 32],
[7, 4, 30],
[8, 0, 85],
[8, 1, 97],
[8, 2, 123],
[8, 3, 64],
[8, 4, 84],
[9, 0, 47],
[9, 1, 114],
[9, 2, 31],
[9, 3, 48],
[9, 4, 94]
], true, true, false);
Live demo: http://jsfiddle.net/BlackLabel/g3snLqwm/
API: https://api.highcharts.com/class-reference/Highcharts.Series#setData
Okay, so I have a multidimensional array that itself contains 9 arrays. Each of these nested arrays contains 10 numeric values. For sake of simplicity, let's say it all looks like this:
var MyArray = [
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10]
]
I am trying to write a function that will take the first index of each nested array (in this case, all 1's) and add them together, pushing this value either to an array or an object. Then, I need this function to continue on, adding all the values of the next index, and the next, and so on and so forth. In the end, I should have an array of 10 values (or an object works here as well). The values would be:
1+1+1+1+1+1+1+1+1,
2+2+2+2+2+2+2+2+2,
3+3+3+3+3+3+3+3+3...
...and so on so forth, so that the actual values of the new array would be this:
[9, 18, 27, 36, 45, 54, 63, 72, 81]
The catch here is that I need this to by flexible/dynamic, so that it will work in case MyArray has only 6 arrays, or maybe the nested arrays have only 4 values each. It should work with any amount of nested arrays, each with their own amount of values (though each nested array will contain the SAME amount of values as one another!).
What would be the best way to accomplish this via JavaScript and/or jQuery? Note that I could also have the values output to an object, in this fashion:
{1:9, 2:18, 3:27, 4:36, 5:45, 6:54, 7:63, 8:72, 9:81}
I tried using similar code to this from another StackOverflow thread to get an object, but it is returning
{1:NaN, 2:NaN, 3:NaN, etc.}
That thread can be found here:
Javascript Multidimensional Array: Add Values
I'm using the "underscore" method and the jQuery $.each part of it provided by Otto.
Anyone able to help here??
Something like this
var myData = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
];
var summed = [];
myData[0].forEach(function (arr, index) {
var sum = myData.reduce(function (a, b) {
return a + b[index];
}, 0);
summed.push(sum);
});
console.log(summed);
On jsfiddle
Here is another solution:
var MyArray = [
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10]
]
var results= [];
MyArray.map(function(a){
for(var i=0;i<a.length;i++){
if(results.length === a.length){
results[i] = results[i] + a[i];
}else{
results.push(a[i]);
}
}
});
http://jsfiddle.net/uMPAA/
A simple array solution would be the following :
var results= [];
for (var i=0;i<MyArray.length;i++) {
for(var j=0; j<MyArray[i].length; j++) {
if(results[j] == undefined) { results[j] = 0; }
results[j] = results[j]+data[i][j];
}
}
Note the if(results[j]==undefined) line -- this is probably what you didn't do. If you omit that, you get NaN on all lines, since you're adding an undefined value to a number.
Another approach to sum columns in multi-dimensional arrays (based on Lodash 4).
var arrays = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
];
function sum_col(arrays) {
return _.map(_.unzip(arrays), _.sum);
}
console.log(sum_col(arrays));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>