JavaScript: find Object with highest summed values from Array - javascript

In need the Object with maximum a+b value from myArray
var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}];
Right now I have something that returns me the index:
var max = [], maxIndex;
myArray.map(x=>max.push(x.a + x.b))
maxIndex = max.indexOf( Math.max.apply(Math, max))
I need something that returns the Object and not its index, so far working with
var maxObject = myArray.map(x=>x.a + x.b).reduce((x,y)=>x>y)
returning false.

You can use reduce like below
var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}];
const finalResult = myArray.reduce((result, obj) => {
let sum = obj.a + obj.b;
if(result.sum < sum) {
return {sum, obj: {...obj}}
}
return result;
}, {sum: 0, obj: {}})
console.log(finalResult.obj)
Hope this helps.

No need for map as reduce will itterate over you array.
var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}];
var biggestSumObj = myArray.reduce((total,current)=>{
if((current.a + current.b) > (total.a + total.b)){
return current;
}
return total;
});
console.log(biggestSumObj);
fiddle: return biggest object

You may try something like that:
let myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}];
let max = myArray[0].a + myArray[0].b;
let maxObject = {...myArray[0]};
myArray.map((obj) => {
if(max < obj.a + obj.b) {
max = obj.a + obj.b;
maxObject = {...obj}
}
});
console.log(maxObject); // { a: 10, b: 7 }

Based on your code, after you found the index of the object with the highest summed values
, you simply return the array in that index:
var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}];
var max = [],
maxIndex;
var result;
myArray.map(x => max.push(x.a + x.b))
maxIndex = max.indexOf(Math.max.apply(Math, max))
result = myArray[maxIndex];
console.log(result);

Related

How to find the most duplicate "values" in javascript array?

my question is actually similar to: Extracting the most duplicate value from an array in JavaScript (with jQuery)
I Found this but it always return one value only which is 200.
var arr = [100,100,200,200,200,300,300,300,400,400,400];
var counts = {}, max = 0, res;
for (var v in arr) {
counts[arr[v]] = (counts[arr[v]] || 0) + 1;
if (counts[arr[v]] > max) {
max = counts[arr[v]];
res = arr[v];
}
}
console.log(res + " occurs " + counts[res] + " times");
pls help me to return values not just one...
The result is should like this:
200,300,400
.
pls help thank you!
You have to iterate your counts to find the max occurred result.
var arr = [100,100,200,200,200,300,300,300,400,400,400];
var counts = {}, max = 0, res;
for (var v in arr) {
counts[arr[v]] = (counts[arr[v]] || 0) + 1;
if (counts[arr[v]] > max) {
max = counts[arr[v]];
res = arr[v];
}
}
var results = [];
for (var k in counts){
if (counts[k] == max){
//console.log(k + " occurs " + counts[k] + " times");
results.push(k);
}
}
console.log(results);
Create a Object iterating the arry containing the indexes of most repeated values, like below
var arr = [100,100,200,200,200,300,300,300,400,400,400];
valObj = {}, max_length = 0, rep_arr = [];
arr.forEach(function(el,i){
if(valObj.hasOwnProperty(el)){
valObj[el] += 1;
max_length = (valObj[el] > max_length) ? valObj[el] : max_length
}
else{
valObj[el] = 1;
}
});
Object.keys(valObj).forEach(function(val){
(valObj[val] >= max_length) && (rep_arr.push(val))
});
console.log(rep_arr);
After the object is created with key as array value and value as array indexes of that value, you can play/parse that. Hope this helps.
Iterating an array using for..in is not a good idea. Check this link for more information.
Hopefully below snippet will be useful
var arr = [100, 100, 200, 200, 200, 300, 300, 300, 400, 400, 400];
//Use a reduce fuction to create an object where 100,200,300
// will be keys and its value will the number of times it has
//repeated
var m = arr.reduce(function(i, v) {
if (i[v] === undefined) {
i[v] = 1
} else {
i[v] = i[v] + 1;
}
return i;
}, {});
// Now get the maximum value from that object,
//getMaxRepeated will be 3 in this case
var getMaxRepeated = Math.max(...Object.values(m));
//An array to hold elements which are repeated 'getMaxRepeated' times
var duplicateItems = [];
// now iterate that object and push the keys which are repeated
//getMaxRepeated times
for (var keys in m) {
if (m[keys] === getMaxRepeated) {
duplicateItems.push(keys)
}
}
console.log(duplicateItems)
The following would do the trick assuming that all items in arr are numbers:
//added some numbers assuming numbers are not sorted
var arr = [300,400,200,100,100,200,200,200,300,300,300,400,400,400];
var obj = arr.reduce(//reduce arr to object of: {"100":2,"200":4,"300":4,"400":4}
(o,key)=>{//key is 100,200, ... o is {"100":numberOfOccurrences,"200":numberOf...}
o[key] = (o[key])?o[key]+1:1;
return o;
},
{}
);
// obj is now: {"100":2,"200":4,"300":4,"400":4}
//create an array of [{key:100,occurs:2},{key:200,occurs:4}...
var sorted = Object.keys(obj).map(
key=>({key:parseInt(key),occurs:obj[key]})
)//sort the [{key:100,occurs:2},... by highest occurrences then lowest key
.sort(
(a,b)=>
(b.occurs-a.occurs===0)
? a.key - b.key
: b.occurs - a.occurs
);
console.log(
sorted.filter(//only the highest occurrences
item=>item.occurs===sorted[0].occurs
).map(//only the number; not the occurrences
item=>item.key
)
);
Try as following ==>
function getDuplicate( arr ){
let obj = {}, dup = [];
for(let i = 0, l = arr.length; i < l; i++){
let val = arr[i];
if( obj[val] /**[hasOwnProperty]*/ ) {
/**[is exists]*/
if(dup.find(a => a == val) ) continue;
/**[put Unique One]*/
dup.push(val);
continue;
};
/**[hold for further use]*/
obj[val] = true;
}
return dup;
};
Use ==>
getDuplicate([100,100,200,200,200,300,300,300,400,400,400]);
Try the following:
var candles = [100,100,200,200,200,300,300,300,400,400,400];
let tempArray = {}
for (let index = 0; index <= (candles.length - 1); index++) {
let valueToCompare = candles[index];
if (tempArray[valueToCompare]) {
tempArray[valueToCompare] = tempArray[valueToCompare] + 1;
} else {
tempArray[valueToCompare] = 1;
}
}
let highestValue;
Object.values(tempArray).forEach(item => {
if (highestValue === undefined) highestValue = item;
if (highestValue < item) highestValue = item;
});
console.log(highestValue);

Calculate percentage from associative array in JS

Suppose I have an array like this:
var arr = [];
arr["india"] = 7;
arr["indonesia"] = 3;
arr["usa"] = 1;
[india: 7, indonesia: 3, usa: 1]
I need to get an array like [india: (7/11*100), indonesia: (3/11*100), usa: (1/11*100)] , i.e., to get the percentage of each country value using a single loop in javascript. How can I achieve it ?
You can use array#reduce to sum up all values and then calculate percentages inside array#map
var arr = {};
arr["india"] = 7;
arr["indonesia"] = 3;
arr["usa"] = 1;
let sum = Object.keys(arr).reduce((s,k) => s += arr[k], 0);
var result = Object.keys(arr).map(k => ({[k] : (arr[k]/sum * 100).toFixed(2)}));
console.log(result);
If your objects is like this var arr = {india: 7, indonesia: 3, usa: 1};, you can do it in this way.
var arr = {india: 7, indonesia: 3, usa: 1};
var sum = 0;
//Finding the sum
for(key in arr){
sum += arr[key];
}
console.log("Sum of the object values is = " + sum);
//Finding the average
for(key in arr){
arr[key] = (arr[key]/sum)*100;
}
console.log(arr);
Loop through each key and reassigned the val like this:
var countries = [];
countries["india"] = 7;
countries["indonesia"] = 3;
countries["usa"] = 1;
for (var country in countries){
if (countries.hasOwnProperty(country)) {
countries[country] = (countries[country] / 11 * 100).toFixed(2)
}
}
console.log(countries)
[india: 7, indonesia: 3, usa: 1]is wrong, you need an object, like {india: 7, indonesia: 3, usa: 1}
So, I think you need an function to do what you need, simple:
var obj = {india: 7, indonesia: 3, usa: 1}
const getPercent = (obj) {
let sum = 0
for (key in obj) {
sum += obj[key]
}
for (key in obj) {
obj[key] = (obj[key]/sum)*100
}
return obj
}
Once you change the obj, you run getPercent(obj), then you get a return, that is what's you need.
May helpful.
So, suppose you have a valid array:
var myArray = { 'key1': 2, 'key2': 5, 'key3': 14 };
/* iterates through an associative array, calculates each percentage and
adds it to a similar associative array
The percentages are not rounded
*/
function getPercentagePerKey(myArray) {
var sum = getSum(myArray);
var arrayWithPercentages = [];
for (key in myArray) {
val = myArray[key];
percentage = (val / sum) * 100;
arrayWithPercentages.push({key, percentage});
}
return arrayWithPercentages;
}
/* returns the sum given from an 'associative' array */
function getSum(myArray) {
var sum = 0;
for (key in myArray) {
sum += myArray[key];
}
return sum;
}
percentageArray = getPercentagePerKey(myArray);
console.log(percentageArray);
0: {key: "key1", percentage: 9.523809523809524}
1: {key: "key2", percentage: 23.809523809523807}
2: {key: "key3", percentage: 66.66666666666666}
You can make getters from object properties if it is allowed:
var arr = {};
arr["india"] = 7;
arr["indonesia"] = 3;
arr["usa"] = 1;
var sum = 0;
var percent = function(n){
return function(){ return n/sum*100; }
}
for (var k in arr) {
sum+=arr[k];
arr[k]=percent(arr[k]);
}
console.log(arr.india());
console.log(arr.usa());
console.log(arr.indonesia());

Get the index of a multidimensional array with the value of a given string in javascript

I have this array,
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
And I want to get the data[0] of the array that have value of "Mary".
So in my example, value that I will get is "absent".
I want also to get the index of the array arr2 that have value of "Josh".
So in my second array, value that I will get is 0.
If possible to use underscore js, we can use it.
I tried to use _.contains() but failed.
Also these array is used in knockout js.
One other way of doing this job could be as follows;
var a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
getIndex = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
console.log(getStatus(a1,"Mary"));
console.log(getIndex(a2,"Sammy Davis"));
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
arr.forEach(function(e,i,a){
if(e[1].indexOf("Mary")>-1){
console.log(e[0])
}
});
arr2.forEach(function(e,i,a){
if(e[1].indexOf("Josh")>-1){
console.log(e[0])
}
});
First using filter() and second findIndex()
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var result1 = arr.filter(x => x[1].indexOf("Mary") !== -1)[0][0];
console.log(result1); // absent
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
var result2 = arr.findIndex(x => x[1].indexOf("Josh") !== -1);
console.log(result2); // 0
If your data set isn't really huge you can store two map objects in memory to quickly access values. Note that this won't work for duplicate names.
The benefit of this approach is that you only have to loop through each array once. If you use any method based on indexOf, you'll loop through your data every time you retrieve a value.
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
var makeKeyMap = function(arr) {
return arr.reduce(function(map, data) {
data[1].forEach(function(key) {
map[key] = data[0];
});
return map;
}, {});
};
var makeIndexMap = function(arr) {
return arr.reduce(function(map, data, index) {
data[1].forEach(function(key) {
map[key] = index;
});
return map;
}, {});
};
var arrMap = makeKeyMap(arr);
var arr2Map = makeIndexMap(arr2);
console.log(arrMap["Mary"]);
console.log(arr2Map["Josh"]);
Edit: a performance test
var myTestData = createTestData();
var randomNameToFind = (function() {
var namesToFind = ["Aileen","Christina","Donna","Judith","Mandy","Sandra","Dawn","Tracey","Mhairi","Victoria","Carolyn","Gayle","Maria","Valerie"];
return function() {
return namesToFind[Math.floor(Math.random() * namesToFind.length)];
}
}());
console.log("Finding the number index for a random name out of 800 names, 10000 times:");
console.time("using index of approach");
var usingIndexOf = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
var results = [];
for (var i = 0; i < 10000; i += 1) {
results.push(usingIndexOf(myTestData, randomNameToFind()));
}
console.timeEnd("using index of approach");
console.time("using map approach");
var makeIndexMap = function(arr) {
return arr.reduce(function(map, data, index) {
data[1].forEach(function(key) {
map[key] = index;
});
return map;
}, {});
};
var myMap = makeIndexMap(myTestData);
results = [];
for (var j = 0; j < 10000; j += 1) {
results.push(myMap[randomNameToFind()]);
}
console.timeEnd("using map approach");
console.log("index map size: " + sizeof(myMap) + " bytes");
// Random data generation code below
function createTestData() {
var names = ["Nicola","Karen","Fiona","Susan","Claire","Sharon","Angela","Gillian","Julie","Michelle","Jacqueline","Amanda","Tracy","Louise","Jennifer","Alison","Sarah","Donna","Caroline","Elaine","Lynn","Margaret","Elizabeth","Lesley","Deborah","Pauline","Lorraine","Laura","Lisa","Tracey","Carol","Linda","Lorna","Catherine","Wendy","Lynne","Yvonne","Pamela","Kirsty","Jane","Emma","Joanne","Heather","Suzanne","Anne","Diane","Helen","Victoria","Dawn","Mary","Samantha","Marie","Kerry","Ann","Hazel","Christine","Gail","Andrea","Clare","Sandra","Shona","Kathleen","Paula","Shirley","Denise","Melanie","Patricia","Audrey","Ruth","Jill","Lee","Leigh","Catriona","Rachel","Morag","Kirsten","Kirsteen","Katrina","Joanna","Lynsey","Cheryl","Debbie","Maureen","Janet","Aileen","Arlene","Zoe","Lindsay","Stephanie","Judith","Mandy","Jillian","Mhairi","Barbara","Carolyn","Gayle","Maria","Valerie","Christina","Marion","Nicola","Karen","Susan","Claire","Fiona","Angela","Sharon","Gillian","Julie","Jennifer","Michelle","Louise","Lisa","Amanda","Donna","Tracy","Alison","Elaine","Jacqueline","Sarah","Caroline","Elizabeth","Laura","Lynn","Deborah","Lesley","Margaret","Joanne","Pauline","Lorraine","Carol","Kirsty","Yvonne","Lorna","Emma","Lynne","Tracey","Heather","Catherine","Pamela","Helen","Linda","Jane","Anne","Kerry","Suzanne","Wendy","Victoria","Diane","Mary","Dawn","Clare","Gail","Paula","Ann","Shona","Hazel","Christine","Andrea","Samantha","Marie","Lynsey","Sandra","Denise","Lee","Kelly","Gayle","Debbie","Jill","Kathleen","Patricia","Joanna","Catriona","Shirley","Ruth","Zoe","Leigh","Rachel","Melanie","Kirsteen","Aileen","Christina","Janet","Katrina","Stephanie","Audrey","Kirsten","Arlene","Maureen","Morag","Marion","Mhairi","Allison","Cheryl","Maria","Kim","Anna","Lindsay","Rebecca","Katherine","Mandy","Nicola","Karen","Claire","Angela","Fiona","Susan","Jennifer","Julie","Gillian","Michelle","Sharon","Sarah","Louise","Donna","Laura","Amanda","Alison","Lisa","Caroline","Kirsty","Jacqueline","Elaine","Lesley","Lynn","Deborah","Elizabeth","Joanne","Emma","Tracy","Lorraine","Lynne","Margaret","Heather","Carol","Lorna","Pauline","Kelly","Helen","Catherine","Linda","Victoria","Suzanne","Kerry","Pamela","Lee","Wendy","Jane","Yvonne","Tracey","Anne","Clare","Mary","Diane","Christine","Lynsey","Samantha","Shona","Andrea","Marie","Gail","Melanie","Dawn","Ann","Paula","Jill","Ruth","Leigh","Hazel","Debbie","Joanna","Denise","Lindsay","Gayle","Patricia","Catriona","Kathleen","Sandra","Leanne","Stephanie","Rachel","Katrina","Shirley","Kirsteen","Janet","Arlene","Zoe","Jillian","Anna","Judith","Mhairi","Natalie","Audrey","Carolyn","Morag","Aileen","Cheryl","Rebecca","Allison","Barbara","Mandy","Claire","Nicola","Karen","Angela","Gillian","Fiona","Jennifer","Laura","Susan","Julie","Michelle","Lisa","Sharon","Louise","Sarah","Tracy","Donna","Kelly","Kirsty","Amanda","Alison","Joanne","Caroline","Emma","Jacqueline","Elaine","Elizabeth","Lynne","Lesley","Deborah","Kerry","Victoria","Carol","Catherine","Lynn","Pauline","Margaret","Lorna","Lynsey","Lorraine","Linda","Suzanne","Tracey","Heather","Yvonne","Jane","Dawn","Mary","Helen","Anne","Wendy","Lee","Pamela","Jill","Lindsay","Clare","Christine","Diane","Leigh","Samantha","Shona","Joanna","Ruth","Debbie","Gail","Marie","Andrea","Paula","Kathleen","Catriona","Katrina","Denise","Melanie","Ann","Sandra","Gayle","Hazel","Jillian","Stephanie","Rachel","Kim","Natalie","Katherine","Patricia","Leanne","Cheryl","Mhairi","Morag","Arlene","Zoe","Kathryn","Aileen","Ashley","Judith","Anna","Frances","Janet","Lucy","Vicky","Christina","Kirsten","Rebecca","Nicola","Claire","Laura","Karen","Michelle","Louise","Jennifer","Fiona","Lisa","Gillian","Angela","Julie","Susan","Sarah","Kelly","Donna","Sharon","Emma","Caroline","Alison","Joanne","Tracy","Kirsty","Lynne","Amanda","Elaine","Jacqueline","Lesley","Kerry","Elizabeth","Lynn","Margaret","Deborah","Catherine","Heather","Lorna","Yvonne","Carol","Lorraine","Suzanne","Lynsey","Victoria","Helen","Linda","Pauline","Dawn","Anne","Jane","Tracey","Clare","Mary","Diane","Jill","Denise","Lee","Leanne","Christine","Shona","Pamela","Samantha","Paula","Joanna","Debbie","Stacey","Hazel","Cheryl","Lindsay","Gail","Rachel","Marie","Ann","Catriona","Andrea","Ruth","Kathryn","Katrina","Mhairi","Wendy","Leigh","Gayle","Melanie","Sandra","Stephanie","Anna","Jillian","Amy","Carolyn","Patricia","Carrie","Natalie","Kathleen","Lyndsey","Ashley","Rebecca","Vicky","Christina","Lindsey","Katherine","Arlene","Sara","Laura","Claire","Nicola","Lisa","Louise","Michelle","Fiona","Karen","Gillian","Jennifer","Emma","Angela","Susan","Kelly","Julie","Donna","Sarah","Kirsty","Sharon","Joanne","Amanda","Tracy","Alison","Elizabeth","Caroline","Elaine","Jacqueline","Lynne","Leanne","Deborah","Lesley","Lorraine","Victoria","Lynn","Pamela","Kerry","Lynsey","Lorna","Carol","Margaret","Heather","Helen","Catherine","Suzanne","Tracey","Yvonne","Cheryl","Linda","Pauline","Debbie","Jane","Dawn","Clare","Lindsay","Mary","Shona","Anne","Rachel","Jill","Christine","Natalie","Samantha","Diane","Lee","Wendy","Joanna","Paula","Marie","Ann","Denise","Catriona","Gayle","Hazel","Kathleen","Stacey","Gail","Ashley","Andrea","Ruth","Anna","Jillian","Leigh","Katrina","Stephanie","Mhairi","Katherine","Sandra","Lyndsey","Christina","Lucy","Patricia","Carrie","Rebecca","Kathryn","Lyndsay","Melanie","Amy","Sara","Arlene","Kirsten","Laura","Claire","Lisa","Nicola","Louise","Karen","Fiona","Jennifer","Michelle","Emma","Sarah","Gillian","Kelly","Susan","Angela","Donna","Kirsty","Julie","Pamela","Joanne","Caroline","Amanda","Tracy","Sharon","Lynne","Elaine","Deborah","Jacqueline","Alison","Lynsey","Victoria","Kerry","Leanne","Lorraine","Lesley","Elizabeth","Lorna","Catherine","Lynn","Suzanne","Heather","Helen","Lindsay","Margaret","Clare","Cheryl","Debbie","Pauline","Dawn","Carol","Mary","Natalie","Linda","Jane","Diane","Stacey","Carrie","Yvonne","Rebecca","Christine","Marie","Charlene","Rachel","Anne","Tracey","Jill","Samantha","Ashley","Paula","Joanna","Stephanie","Andrea","Shona","Denise","Anna","Hazel","Katrina","Ruth","Gayle","Lee","Sara","Catriona","Kathryn","Leigh","Mhairi","Wendy","Amy","Jillian","Katherine","Gail","Linsey","Christina","Lucy","Melanie","Sandra","Ann","Kathleen","Shelley","Kirsten","Kim","Lyndsey","Laura","Claire","Lisa","Nicola","Emma","Louise","Jennifer","Michelle","Sarah","Fiona","Karen","Gillian","Kirsty","Donna","Kelly","Pamela","Susan","Julie","Angela","Amanda","Lynsey","Sharon","Lynne","Deborah","Joanne","Victoria","Caroline","Alison","Leanne","Gemma","Elaine","Jacqueline","Lesley","Elizabeth","Lorraine","Kerry","Heather","Debbie","Catherine","Lynn","Lorna","Tracy","Suzanne","Yvonne","Cheryl","Natalie","Margaret","Lindsay","Diane","Helen","Pauline","Ashley","Rachel","Clare","Carol","Christine","Linda","Dawn","Rebecca","Stephanie","Jill","Tracey","Jane","Stacey","Paula","Shona","Anna","Charlene","Anne","Marie","Catriona","Samantha","Joanna","Ruth","Andrea","Mary","Denise","Kim","Mhairi","Hazel","Lauren","Amy","Kathryn","Carrie","Lyndsey","Lucy","Gail","Katherine","Christina","Linsey","Wendy","Katrina","Kimberley","Ann","Lee"];
var nameMap = names.reduce((map, n) => {
map[n[0]] = map[n[0]] || [];
map[n[0]].push(n);
return map;
}, {});
var testData = Object.keys(nameMap)
.sort()
.reduce((res, k) => {
res.push([k, nameMap[k]]);
return res;
}, []);
return testData;
};
<script src="http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/sizeof.compressed.js"></script>

How to get the property with the largest number?

I need to return a new object from an original object.
The original object's property values are numbers bigger than 0, and I want to return the property with the largest value.
Edit: I want to return the largest property only if the property's $.isNumeric() is true; Apologies for my poor English.
obj = {2:1, 3:4, a:8, 5:2, 4:5 }; //expected newobj = {5:5};
Largest number in an array of strings (ignoring non-numeric):
function maxInArr(arr) {
return Math.max.apply(void 0, arr.filter($.isNumeric).map(Number));
}
Largest property:
var maxProp = maxInArr(Object.keys(obj));
Largest value:
var maxVal = maxInArr(Object.keys(obj).map(function(p){
return obj[p];
}));
Build the object:
var obj2 = {};
obj2[maxProp] = maxVal;
obj2; // {5: 8}
Try putting your array into this simple function:
function heighest(yourArray) {
var keys = Object.keys(yourArray);
var values = Object.keys(yourArray);
for (int i = 0; i < keys.length; i++)
{
keys[i] = parseInt(keys[i]);
values[i] = parseInt(values[i]);
}
var highestKey = Math.max.apply(Math, keys);
alert('Heighest key: ' + highestKey + ', with value ' + yourArray[highestKey]);
};
If I understood question correctly this should be possible answer.
var obj = {2:1, 3:4, a:8, 5:2, 3:5, 3:5};
var max = Number.MIN_VALUE;
for(var propertyName in obj) {
if(!isNaN(propertyName) && propertyName > 0){
if(obj.hasOwnProperty(propertyName) && obj[propertyName] > max){
max = obj[propertyName];
}
}
}
console.log(max);
Here is jsfiddle: http://jsfiddle.net/4bLe9jbj/1/

Javascript Multidimensional Array: Add Values

So I have a multidimensional array like:
myArr = [["venue",2],["venue",16],["inning",2],["inning",4],["inning",32],["hithard", 4]]
I would like to add the similar values up. So in the end I just have:
"venue" = 18, "inning" = 38, and "hithard" = 4.
Can you give me an example of how to accomplish this? Either with Javascript and/or jQuery
Thanks!
I am not sure if you want an array or object. If object, stop it is 1st pass and tmp in below code should return you the object as Object { venue=18, inning=38, hithard=4}.
DEMO
var tmp = {}, keys;
for (var i = 0; i < myArr.length; i++) {
keys = myArr[i][0];
tmp[keys] = (tmp.hasOwnProperty(keys))?
(tmp[keys] + myArr[i][1]):myArr[i][1];
} //tmp - will return you a Object { venue=18, inning=38, hithard=4}
var output = [];
for (keys in tmp) {
output.push([keys, tmp[keys]]);
} //output will return you an array as [["venue", 18],["inning", 38],["hithard", 4]]
myArr = [["venue",2],["venue",16],["inning",2],["inning",4],["inning",32],["hithard", 4]];
values = {};
for (i=0;i<myArr.length;i++){
if ("undefined" == typeof values[myArr[i][0]]) {values[myArr[i][0]] = 0;}
values[myArr[i][0]] += myArr[i][1];
}
arr = [];
query_string = "";
for (i in values) {
// if you want it in an array:
arr.push('"' + i + '" = ' + values[i]);
query_string += (query_string.length ? "&" : "") + i + "=" + values[i];
}
​console.log(arr);​
DEMO: http://jsfiddle.net/Ta97E/2/
you can use values to create the query string
Check this code:
var final = {};
for (var i in myArr) {
var item = myArr[i];
final[item[0]] = (final[item[0]] || 0) + item[1];
}
console.log(final);​
DEMO: http://jsfiddle.net/UVJEb/
Underscore solution:
sums = _.reduce(myArr, function (obj, item) {
obj[item[0]] = (obj[item[0]] || 0) + item[1];
return obj;
}, {});
// sums = {"venue":18,"inning":38,"hithard":4}
A little dirtier in jQuery
sums = {}
$.each(myArr, function (i, value) {
sums[value[0]] = (sums[value[0]] || 0) + value[1];
});
Edit: add jQuery version

Categories

Resources