JS: Get RGBA value out of a string - javascript

I'm using the current code, suggested here on SO, to get the RGB values from a string like "rgb(0, 0, 0)" but also it can be "rgb(0, 0, 0,096)", so now i need to get also the alpha value
function getRGB(str) {
var match = str.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)?(?:, ?(\d(?:\.\d?))\))?/);
arr = [match[1], match[2], match[3]];
return arr;
}
I tried this code below but it doesn't work
function getRGBA(str) {
var match = str.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)?(?:, ?(\d(?:\.\d?))\))?/);
arr = [match[1], match[2], match[3], match[4]];
return arr;
}

Your original regex is already allowing for the alpha (there are four sets of digits with commas between, where the fourth is optional; also note that the a in rgba near the beginning is optional because of the ? after it). You can tell whether you got the alpha by looking at match[4]:
function getRGB(str) {
var match = str.match(/rgba?\((\d{1,3}), ?(\d{1,3}), ?(\d{1,3})\)?(?:, ?(\d(?:\.\d?))\))?/);
arr = [match[1], match[2], match[3]];
if (match[4]) { // ***
arr.push(match[4]); // ***
} // ***
return arr;
}
Not strictly what you asked, but that regular expression has a few issues that will prevent it from reliably detecting strings:
It only allows one space after commas, but more than one space is valid
It doesn't allow for any spaces before commas
In the alpha part, it allows for 1. but that's invalid without a digit after the .
A couple of other notes:
That code relies on what I call The Horror of Implicit Globals because it never declares arr.
The code isn't converting the values to numbers. I don't know if you wanted to do that or not, but I figured it was worth noting.
The function throws an error if the string doesn't match the expression. Maybe that's what you want, but again I thought I'd flag it up.
This expression does a better job of matching:
/rgba?\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:\)|,\s*(\d?(?:\.\d+)?)\))/
Live Example:
function num(str) {
str = str.trim();
// Just using + would treat "" as 0
// Using parseFloat would ignore trailing invalid chars
// More: https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875
return str === "" ? NaN : +str;
}
function getRGB(str) {
const match = str.match(/rgba?\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:\)|,\s*(\d?(?:\.\d+)?)\))/);
if (!match) {
return null;
}
const arr = [
num(match[1]),
num(match[2]),
num(match[3])
];
if (match[4]) {
arr.push(num(match[4]));
}
return arr;
}
function test(str) {
console.log(str, "=>", JSON.stringify(getRGB(str)))
}
test("rgb(1,2,3,4)"); // [1, 2, 3, 4]
test("rgba(1 , 2, 3, 4)"); // [1, 2, 3, 4]
test("rgba(111 , 22, 33)"); // [111, 22, 33]
test("rgb(111, 22)"); // null (doesn't match)
test("rgb(111, 22 , 33, 1)"); // [111, 22, 33, 1]
test("rgb(111, 22, 33, 1.)"); // null (doesn't match, no digit after .)
test("rgb(111, 22, 33, 1.0)"); // [111, 22, 33, 1]
test("rgb(111, 22, 33, .5)"); // [111, 22, 33, 0.5]
.as-console-wrapper {
max-height: 100% !important;
}
And in modern JavaScript environments we could make it a bit simpler to use by using named capture groups (see the live example for the num function and why I use it rather than +/Number or parseFloat):
function getRGB(str) {
const {groups} = str.match(
/rgba?\((?<r>\d{1,3})\s*,\s*(?<g>\d{1,3})\s*,\s*(?<b>\d{1,3})\s*(?:\)|,\s*(?<a>\d?(?:\.\d+)?)\))/
) ?? {groups: null};
if (!groups) {
return null;
}
const arr = [
num(groups.r),
num(groups.g),
num(groups.b)
];
if (groups.a) {
arr.push(num(groups.a));
}
return arr;
}
Live Example:
function num(str) {
str = str.trim();
// Just using + would treat "" as 0
// Using parseFloat would ignore trailing invalid chars
// More: https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875
return str === "" ? NaN : +str;
}
function getRGB(str) {
const {groups} = str.match(
/rgba?\((?<r>\d{1,3})\s*,\s*(?<g>\d{1,3})\s*,\s*(?<b>\d{1,3})\s*(?:\)|,\s*(?<a>\d?(?:\.\d+)?)\))/
) ?? {groups: null};
if (!groups) {
return null;
}
const arr = [
num(groups.r),
num(groups.g),
num(groups.b)
];
if (groups.a) {
arr.push(num(groups.a));
}
return arr;
}
function test(str) {
console.log(str, "=>", JSON.stringify(getRGB(str)))
}
test("rgb(1,2,3,4)"); // [1, 2, 3, 4]
test("rgba(1 , 2, 3, 4)"); // [1, 2, 3, 4]
test("rgba(111 , 22, 33)"); // [111, 22, 33]
test("rgb(111, 22)"); // null (doesn't match)
test("rgb(111, 22 , 33, 1)"); // [111, 22, 33, 1]
test("rgb(111, 22, 33, 1.)"); // null (doesn't match, no digit after .)
test("rgb(111, 22, 33, 1.0)"); // [111, 22, 33, 1]
test("rgb(111, 22, 33, .5)"); // [111, 22, 33, 0.5]
.as-console-wrapper {
max-height: 100% !important;
}

Related

best way to search and delete with given values, for delete from array inside the object and return new array of object javascript?

I have tried a couple of methods using findIndex, map, Object.entires
someone help me find the best solution?
**
remove 2 from customerNumber array [1,2,3,4,5]
set to customerNumber value with array[1,3,4,5]
and spread customerNumber to filterState array
**
let filterState = [
{'customerNumber': [1,2,3,4,5]},
{'ward': [10, 20, 30, 40, 50]},
{'enrolledDate': [111, 222,333, 444,555]},
{'district': ['AAA', 'BBB','CCCC', 'DDD']},
{'onBoardingSmsStatus': false}
]
search and delete 2 from customerNumber//customerNumber : 2
function removedChip(type='', value=0, filterState=[]) {
for(let i=0; i<filterState.length; i++) {
let entries = Object.keys(filterState)
.forEach(function eachKey(key) {
console.log(key); // alerts key
console.log(filterState[key]); // alerts value
});
console.log(entries)
let searchIndex = entries.findIndex(type);
console.log('searchIndex', searchIndex)
console.log('type of ', filterState[searchIndex])
for(let i=0; i<filterState[searchIndex]; i++) {
//remove 2 from customerNumber array [1,2,3,4,5]
// set to customerNumber value with array[1,3,4,5]
// and spread customerNumber to filterState array
}
}
}
function invoking with values
removedChip('customerNumber', 10, filterState)
the expected output is
let filterState = [
{'customerNumber': [1,3,4,5]},
{'ward': [10, 20, 30, 40, 50]},
{'enrolledDate': [111, 222,333, 444,555]},
{'district': ['AAA', 'BBB','CCCC', 'DDD']},
{'onBoardingSmsStatus': false}
]
This might help :
function removedChip(type='', value=0, filterState=[]) {
const filterStateTypeArray = filterState.filter(fs =>
Object.keys(fs)[0] === type);
const filterStateTypeItem = filterStateTypeArray ?
filterStateTypeArray[0] : null;
if(!filterStateTypeItem){return;}
let valueArray = filterStateTypeItem[type];
valueArray = valueArray.filter(vA => vA !== value);
filterStateTypeItem[type] = valueArray;
console.log(filterState);
}
let filterState = [
{'customerNumber': [1,2,3,4,5]},
{'ward': [10, 20, 30, 40, 50]},
{'enrolledDate': [111, 222,333, 444,555]},
{'district': ['AAA', 'BBB','CCCC', 'DDD']},
{'onBoardingSmsStatus': false}
]
removedChip('customerNumber', 2, filterState);
Not much of a change from other answers which are all feasible - I'd just split out the functions in 2 to have the filtering handled for an array which can then be tested independently of the parent function or independently from whatever list of objects is inputted
I.e you can have a generic filtering method that can be tested in isolation from the input list of objects.
let filterState = [
{ customerNumber: [1, 2, 3, 4, 5] },
{ ward: [10, 20, 30, 40, 50] },
{ enrolledDate: [111, 222, 333, 444, 555] },
{ district: ['AAA', 'BBB', 'CCCC', 'DDD'] },
{ onBoardingSmsStatus: false },
];
// Independent testable filtering
const removeChipFromArray = (array, removeValue = 0) => {
return array.filter(e => e !== removeValue);
};
// Function to handle the removal of any value from any list of objects
const removeChips = (listOfObjects, value) => {
listOfObjects.forEach((element, index) => {
const key = Object.keys(element);
// General type checker (which would be easier in TS than JS but here is a half-safe way of ensuring you're operating against a list
// You could also convert it to an Array if you think that's better
if (typeof(element[key]) === 'object') {
element[key] = removeChipFromArray(element[key], value);
}
});
};
removeChips(filterState, 2);
console.log(filterState);
In your removedChip You can filter it like..
function removedChip(type = "", value = 0, filterState = []) {
const result = filterState.map((data) => {
if (data[type]) {
// Modify only the given field in the type params
return { [type]: data[type].filter((du) => du !== value) };
}
return data;
});
return result;
}
let filterState = [
{ customerNumber: [1, 2, 3, 4, 5] },
{ ward: [10, 20, 30, 40, 50] },
{ enrolledDate: [111, 222, 333, 444, 555] },
{ district: ["AAA", "BBB", "CCCC", "DDD"] },
{ onBoardingSmsStatus: false }
];
console.log(removedChip("customerNumber", 2, filterState));

max with condition in Javascript

I have two arrays:
search array: [['#S!', 1, 1], ['#$#', 2, 5], ['#S!', 10, 12], ['#$#', 21, 5]]
and key array: ['#S!','#$#']
I want to look up into search array based on the key array element and create a resultant array which looks like this:
[[key array element,max while lookup for value at index 1 in search array, max while lookup for value at index 2 in search array], [...]]
Here is my code for the same:
let resultant = [];
keys.forEach((ele, ind) => {
resultant[ind] = [
ele,
Math.max(searchArray.filter(element => element[0] === ele)),
Math.max(searchArray.filter(element => element[0] === ele))
];
});
Now I am confused in these statements:
Math.max(newSet.filter(element => element[0] === ele)),
Math.max(newSet.filter(element => element[0] === ele))
Because filter will return the entire array but I want to find max of element with index 1 and in second statement I want to return max of element with index 2 which have the element with index 0 same as the key which I have provided.
Here is one simple test case:
search Array: [["A",1,2],["A",12,23],["A",11,23],["A",14,42],["A",71,32],["B",113,42],["B",145,62],["C",91,32],["C",14,222],["C",111,2]]
keys Array: ["A","B","C"]
Output: [["A",71,42],["B",145,62],["C",111,222]]
As you can see max corresponding to the elements are mapped to the same elements. Can someone help me with this? Is there a better or more optimized algorithm for the same than what I am using?
You could take a dynamic approach with an object for the wanted keys.
function max(search, keys) {
const temp = search.reduce((r, [key, ...data]) => {
if (!r[key]) r[key] = [key, ...data];
else data.forEach((v, i) => { if (r[key][i + 1] < v) r[key][i + 1] = v; });
return r;
}, {});
return keys.map(key => temp[key]);
}
console.log(max([['#S!', 1, 1], ['#$#', 2, 5], ['#S!', 10, 12], ['#$#', 21, 5]], ['#S!','#$#']));
console.log(max([["A", 1, 2],["A", 12, 23],["A", 11, 23], ["A", 14, 42], ["A", 71, 32], ["B", 113, 42], ["B", 145, 62], ["C", 91, 32], ["C", 14, 222], ["C", 111, 2]], ["A", "B", "C"]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try use js array flatten method to do this,
let searchArray = [["A",1,2],["A",12,23],["A",11,23],["A",14,42],["A",71,32],["B",113,42],["B",145,62],["C",91,32],["C",14,222],["C",111,2]];
let keysArray = ["A","B","C"];
console.clear();
let output = [];
keysArray.forEach(item => {
let groupSearchArray = searchArray.filter(f => f[0] === item);
let sortedArray = groupSearchArray.flat(1).filter(f => f !== item).sort().reverse();
output.push([item, sortedArray[0], sortedArray[1]]);
});
console.log(output);

How to search a value in Object which has values in array as well?

I've an object as below;
FOO: {
BAR: [9,32,8,12 ],
ZET: 4,
BETA: [3,14,6,2],
ALPHA: 37
},
I need to search values of this object to match values with keys. There are tons of samples which gives keys with a singular value but I couldn't find any sample which also able to search in values those are in arrays.
How can I be able to search whole of those values of FOO object and match with keys?
Note: The aim; I'll looking for an input and if given input is 2 then expect to get the key BETA or if given input is 4 then ZET.
So basically the values will be some pre-defined unique values already.
You could get the keys, create an array of values and check with includes. Return the found key.
function find(object, value) {
return Object
.keys(object)
.find(k => [].concat(object[k]).includes(value));
}
var object = { FOO: { BAR: [9, 32, 8, 12], ZET: 4, BETA: [3, 14, 6, 2], ALPHA: 37 } };
console.log(find(object.FOO, 4));
console.log(find(object.FOO, 8));
You can do it with a simple for...in loop and .concAT() and .includes() methods of arrays:
let obj = {
BAR: [9,32,8,12 ],
ZET: 4,
BETA: [3,14,6,2],
ALPHA: 37
};
let locator = (o, v) => {
for (var prop in o) {
if([].concat(o[prop]).includes(v)){
return prop;
}
}
}
console.log(locator(obj, 2));
console.log(locator(obj, 4));
You can simply loop though the object and search for the value to identify the key. If multiple matches are found, an array of keys that matches the result will be returned.
function objSearch(key, obj) {
const keys = [];
for (let item in obj) {
if (obj.hasOwnProperty(item)) {
if (obj[item] === key || (Array.isArray(obj[item]) && obj[item].indexOf(key) > -1)) {
keys.push(item);
}
}
}
return keys;
}
const obj = {
FOO: {
BAR: [9, 32, 8, 12],
ZET: 4,
BETA: [3, 14, 6, 2],
ALPHA: 37
}
};
const res1 = objSearch(14, obj.FOO); // Exist
const res2 = objSearch(15, obj.FOO); // Does not exist
const res3 = objSearch(37, obj.FOO); // Exist
console.log(res1);
console.log(res2);
console.log(res3);
Try this snippet,
I am checking conditions for object values whether its array or value and applied condition as per that. I kept parent key dynamic too.
var abc = {
FOO: {
BAR: [9, 32, 8, 12],
ZET: 4,
BETA: [3, 14, 6, 2],
ALPHA: 37
},
DAB: {
DBAR: [9, 32, 8, 12],
DZET: 4,
DBETA: [3, 14, 6, 2],
DALPHA: 37
},
};
function retTitle(abc, parent, k) {
var title = '';
$.each(abc[parent], function(x, y) {
if ((Array.isArray(y) && y.indexOf(k) != -1) || (!Array.isArray(y) && y == k)) {
title = x;
return;
}
});
return title;
}
var title = retTitle(abc, 'DAB', 4);
console.log(title);
Something like this should work:
// What we're searching
FOO = {
BAR: [9,32,8,12 ],
ZET: 4,
BETA: [3,14,6,2],
ALPHA: 37
};
function findValue(findValue, obj) {
return Object.entries(FOO)
.filter(([key,value]) => value === findValue || Array.isArray(value) && value.includes(findValue))
.map(([key,value])=> key);
}
function testfindValue(value, obj) {
console.log("testfindValue: \nInput: " + value, "Result: ", findValue(value,obj));
}
testfindValue(4, FOO);
testfindValue(6, FOO);
testfindValue(32, FOO);
testfindValue(99, FOO);
You can use a simple for...in loop to iterate over keys. Then check if the value is a number and equals to what you look for. If it's not a number then it's an array - so you check that this array includes the number you are looking for.
var FOO = {
BAR: [9,32,8,12 ],
ZET: 4,
BETA: [3,14,6,2],
ALPHA: 37
};
function findKeyByValue(obj, val) {
for (var i in FOO) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof FOO[i] === 'number') {
if(FOO[i] === val) return i;
} else {
if(FOO[i].includes(val)) return i;
}
}
}
console.log(findKeyByValue(FOO, 4));

Accessing a JSON integer element

I have an JSON-Object as follows:
Input for the months is
customerSend,customerReceived,totalSendAllCustomers,totalReceivedAllCustomers
var emailObj = {
"kundenNummer":17889,
"jahre":
{
2017:{
"Januar":[15,30,75,125],
"Februar":[17,32,77,127],
"März":[19,34,79,129],
},
2018:{
"Januar":[28,12,66,198],
"Oktober":[40,4,40,5],
}
}
}
How exactly do I access the specific year?
I already tried it like this:
var keysYears = Object.keys(emailObj.jahre);
var currentSelectedYear = keysYears[0];
var keysMonth = Object.keys(emailObj.jahre[currentSelectedYear]);
var currentSelectedMonth = keysMonth[0];
document.write(emailObj.jahre[currentSelectedYear].2017[0]);
I also tried some other ways of doing this but I already deleted those.
Can you tell me how to access the 2017 or 2018 data?
I know that I could convert them into strings but I want to know if I could also do it this way.
You can call the properties of your object emailObj by their names.
Either with a dot notation
emailObj.kundenNummer
Or by brackets notation
emailObj["kundenNummer"]
The dot notation won't work in your case because the name of your property is a number. You should then use
emailObj.jahre["2017"]
var emailObj = {
"kundenNummer": 17889,
"jahre": {
"2017": {
"Januar": [15, 30, 75, 125],
"Februar": [17, 32, 77, 127],
"März": [19, 34, 79, 129],
},
"2018": {
"Januar": [28, 12, 66, 198],
"Oktober": [40, 4, 40, 5],
}
}
};
let year = "2017";
let month = "Januar";
console.log(emailObj.jahre[year][month]);
You should use bracket notation.
document.write(emailObj.jahre[currentSelectedYear][currentSelectedMonth][0]);
var emailObj = {
"kundenNummer":17889,
"jahre":
{
2017:{
"Januar":[15,30,75,125],
"Februar":[17,32,77,127],
"März":[19,34,79,129],
},
2018:{
"Januar":[28,12,66,198],
"Oktober":[40,4,40,5],
}
}
}
var keysYears = Object.keys(emailObj.jahre);
var currentSelectedYear = keysYears[0];
var keysMonth = Object.keys(emailObj.jahre[currentSelectedYear]);
var currentSelectedMonth = keysMonth[0];
document.write(emailObj.jahre[currentSelectedYear][currentSelectedMonth][0]);
In a JavaScript object, the key is always a string, even if you use an integer it will be converted into a string.
obj = {
key1: //contents
key2: //contents
}
To access a specific key:
obj.key1
obj['key1']
For your example:
emailObj.jahre['2017']
emailObj['jahre']['2017']
Use the for in looping construct to loop through the keys of an object:
var emailObj = {
"kundenNummer":17889,
"jahre": {
2017:{
"Januar":[15,30,75,125],
"Februar":[17,32,77,127],
"März":[19,34,79,129],
},
2018:{
"Januar":[28,12,66,198],
"Oktober":[40,4,40,5],
}
}
}
for (key in emailObj.jahre) {
console.log(emailObj.jahre[key]) //Here key will be '2017', '2018' etc
}
You cannot access with dot notation properties which contain as name a number in JavaScript. Instead you should consider using bracket notation.
Example:
emailObj.jahre['2017']
var emailObj = {
"kundenNummer": 17889,
"jahre": {
2017: {
"Januar": [15, 30, 75, 125],
"Februar": [17, 32, 77, 127],
"März": [19, 34, 79, 129],
},
2018: {
"Januar": [28, 12, 66, 198],
"Oktober": [40, 4, 40, 5],
}
}
};
console.log(emailObj['jahre']['2017']);
console.log(emailObj.jahre['2017']);

calculate average result from multi-dimensionally sorted array (JavaScript)

Below is the layout of my JSON File.
{
"questions": ["Question1", "Question2"],
"orgs": ["Org1", "Org2", "Org3"],
"dates": ["Q1", "Q2", "Q3"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
]
]
}
I'm trying to retrieve a single array of values by looping through each question, indexed by an "orgs" value and then adding each value retrieved and dividing it by data.dates.length.
Here is my code;
d3.json("data.json", function(error, data) {
var array = new Array()
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
for (var question = 0; question < data.questions.length; question++) {
array.push(
data.values[question][org]
)
console.log(array)
}
// add array together
array.reduce(function(a, b) {
return a + b;
})
// calculate average
var avg = array / data.dates.length;
})
Here is a plnk;
http://plnkr.co/edit/wMv8GmkD1ynjo9WZVlMb?p=preview
I think the issue here is how I'm retrieving the values in the first place? as at the moment, although I am retrieving the correct values in the console log, I'm getting the array twice, and both times inside nested arrays. I'm not so sure how to remedy the problem?
For reference;
[question1][org1] corresponds to the values [5, 88, 18].
Hope someone can offer some advice here?
Thanks!
Since you clarified your question to indicate you want to calculate separate averages for each question, I've rewritten my answer. You should do all the calculations in the for loop, since the loop is looping through the questions. Then store your averages in an array.
d3.json("data.json", function(error, data) {
var averages = new Array()
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
var values, sum;
for (var question = 0; question < data.questions.length; question++) {
// get the values for the question/org
values = data.values[question][org];
// calculate the sum
sum = values.reduce(function(a, b) {
return a + b;
});
// calculate the average
averages.push(sum / values.length);
}
console.log(averages);
});
Perform the .reduce() in the for loop and push that result into array. That will give you the an array of the results you expected.
array.push(data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length)
[
47.666666666666664,
43.666666666666664
]
Currently, you're attempting to perform addition on the arrays themselves in the .reduce() callback instead of reducing the members of each individual array to their sum, and then average.
Demo: (Click the text below to show the whole function)
var data = {
"questions": ["Question1", "Question2"],
"orgs": ["Org1", "Org2", "Org3"],
"dates": ["Q1", "Q2", "Q3"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
]
]
}
x(data)
// Your callback function.
function x(data) {
var array = new Array()
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
for (var question = 0; question < data.questions.length; question++) {
array.push(data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length)
}
console.log(array)
}
Instead of a for loop, you could also use .map().
var array = data.questions.map(function(_, question) {
return data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length
})
Demo: (Click the text below to show the whole function)
var data = {
"questions": ["Question1", "Question2"],
"orgs": ["Org1", "Org2", "Org3"],
"dates": ["Q1", "Q2", "Q3"],
"values": [
[
[5, 88, 18],
[50, 83, 10],
[29, 78, 80]
],
[
[46, 51, 61],
[95, 21, 15],
[49, 86, 43]
]
]
}
x(data)
// Your callback function.
function x(data) {
var orgS = "Org2"
var org = data.orgs.indexOf(orgS);
var array = data.questions.map(function(_, question) {
return data.values[question][org].reduce(function(a, b) {
return a + b
}, 0) / data.dates.length
})
console.log(array)
}
You need to store the sum, the result of reduce.
// add array together
// store in sum
var sum = array.reduce(function(a, b) {
return a + b;
}, 0); // use 0 as start value
For the average, you do not need the length of data.dates but from array, because you collecting the values and this length is important.
// calculate average
var avg = sum / array.length;
Together for all values, you might get this
var data = { "questions": ["Question1", "Question2"], "orgs": ["Org1", "Org2", "Org3"], "dates": ["Q1", "Q2", "Q3"], "values": [[[5, 88, 18], [50, 83, 10], [29, 78, 80]], [[46, 51, 61], [95, 21, 15], [49, 86, 43]]] },
sum = [];
data.values.forEach(function (a, i) {
sum[i] = sum[i] || [];
a.forEach(function (b) {
b.forEach(function (c, j) {
sum[i][j] = sum[i][j] || 0;
sum[i][j] += c;
});
});
});
data.avg = sum.map(function (a, i) {
return a.map(function (b) {
return b / data.values[i].length;
});
});
console.log(sum);
console.log(data);

Categories

Resources