I have the following object:
{"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"}
I want to sum all this values and print It out. How can I sum the properties values? :)
Iterate over the object properties using for(var in)
Use parseInt since some of the integers are in string form
var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
var sum = 0;
for(var key in obj){
sum += parseInt(obj[key]);
}
document.write(sum);
Here's a way of doing it using ES5's Object.keys and reduce:
var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
var sum = Object.keys(obj).reduce(function(prev, current, index) {
return prev + (+obj[current]);
}, 0);
console.log(sum); // 746
jsFiddle
My for-less version:
var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
function sumProperties(obj) {
return Object.getOwnPropertyNames(obj)
.map(function(item){ return +obj[item];})
.reduce(function(acc,item) { return acc + item; });
}
document.write(sumProperties(obj));
Given
var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional": 299}
you can do it very easily with the lodash library:
var result = _.sum(obj);
If some of your values aren't numbers, you need to map them to numbers first:
var result = _.sum(_.map(obj, function(n){
return +n;
//or parseInt(n) or parseInt(n,10)
}));
http://plnkr.co/edit/UQs1aTCJ8qe1kG15G4x7?p=preview
You can do it this way:
var sum_object = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
var sum = 0;
for( var index in sum_object ){
sum += parseInt(sum_object[index]);
console.log("Val: ",sum_object[index], sum);
};
console.log(sum);
JSFiddle: http://jsfiddle.net/abvuh5m0/
var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
function sum(obj){
var sum = 0;
for(var key in obj){
if (obj. hasOwnProperty(key)) {
sum += parseInt(obj[key]) || 0;
}
}
return sum
}
console.log(sum(obj));
parseInt(obj[key]) || 0; is important id the value is not a number
Using Lodash:
var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
var val = _.sumBy(_.values(obj), function(v) {
return parseInt(v)
});
Example: https://codepen.io/dieterich/pen/dyymoxM?editors=0012
var sum = 0;
for(var key in objects) {
sum += parseInt(objects[key]);
}
console.log(sum);
Related
How to count the JSON object and on the basis of count take the same output
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
First I would like the count after it on the basis of count. I want same output like input.
for Count:-
var count = 0;
function getCount() {
for (var i = 0; i < obj.length; i++) {
count++;
}
return count;
}
for output :-
function showDetails() this is not giving the proper output
{
for(var j=0; j< count; j++){
obj.push([{j}]);
}
alert(obj.name);
}
alert(showDetails());
And I want an output like:-
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
Can anybody help me please?
var data ="January,February,March,April,May,June,July,August,September,October";
var obj = data.split(',').map((item)=>{
return {
name:item
}
});
obj will be the desired output
var str = "January,February,March,April,May,June,July,August,September,October";
var arr = str.split(',').map(function(v) {
return {name: v};
});
console.log(arr);
var str = "January,February,March,April,May,June,July,August,September,October";
var months = str.split(",");
var result = [];
for (i in months)
{
var month = {};
month.name = months[i];
//you can do more things else here, for example:
//month.monthOfYear = (i+1);
//month.numberOfDay = 123123123;
result.push(month);
}
You can do something like this:
var array = string.split(",");
var finalArray = [];
array.forEach(function(item){
var obj = {
name: item
}
finalArray.push(obj);
});
console.log(finalArray);
MDN reference
use var array = string.split(',');
For a more ES2015 heavy version. Constants, arrow function and implicit return statement.
const str = 'January,February,March,April,May,June,July,August,September,October'
const result = str.split(',').map(name => ({name}))
console.log(result)
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/
My function is
var MyArray= [];
$('input:checked').each(function(index) {
MyArray= ($(this).attr('id') + ":" + $(this).val()).length;
});
My array is
Array [ "1:R1", "2:R2", "3:R3", "4:R1" ]
I would like to count the differents values and to get this object
Object {R1:2, R2:1, R3:1}
Instead of putting the values in an array and then get the values out of the array to process them and create an object, put them in the object to start with:
var map = {};
$('input:checked').each(function() {
var key = $(this).val();
if (key in map) {
map[key]++;
} else {
map[key] = 1;
}
});
Demo: http://jsfiddle.net/Guffa/0a35c6yp/
You can convert your var with this code :
var arr = [ "1:R1", "2:R2", "3:R3", "4:R1" ];
var obj = {};
for(var i=0, l=arr.length; i<l; i++) {
var parts = arr[i].split(':');
if(parts.length > 1) {
if(!obj[parts[1]]) {
obj[parts[1]] = 0;
}
obj[parts[1]]++
}
}
console.log(obj)
Or create directly the correct object :
var obj = {};
$('input:checked').each(function (index) {
var key = $(this).val();
if (!obj[key]) {
obj[key] = 0;
}
obj[key]++
});
Use a regex to capture the correct portion of the string, and add them as keys to the object, incrementing the value if it already exists:
var regex = /\d+:(R\d+)/
var obj = {};
arr.forEach(function (el) {
var key = el.match(regex)[1];
if (!obj[key]) obj[key] = 0;
obj[key]++;
});
DEMO
You could try something like that:
Write your Array into a Map and step up your value each time your map already knows the key.
for(var i = 0; i < myArray.length; i++){
var entry = myArray[i];
var key = entry.split(":")[1];
if(myMap.has(key))
myMap.set(key, myMap.get(key) + 1);
else
myMap.set(key, 1);
}
DEMO
I have a collection of array-like objects like this :
a = [[1,2],[3,4],[5,6],[7,8]]
And I would like to sum the columns (if u think of this as a 4x2 array) such that:
col1_sum = 16
col2_sum = 20
What is the best way of doing this is JS?
I tried using underscore's _.reduce function like so:
var col1_sum =_.reduce(a, function(memo,obj){ return memo + parseFloat(obj[0]);},0)
but I get an "undefined" error
any ideas? thank you.
You could always kick it old school. It's not pretty, but it works.
col1_sum = 0;
col2_sum = 0;
for (var i = 0; i < a.length; ++i) {
col1_sum += a[i][0];
col2_sum += a[i][1];
}
My other thought was to use jQuery's each function, but I guess you're not looking for a jQuery solution?
EDIT - Who needs jQuery.each? Just use JavaScript's Array.forEach:
var col1_sum = 0;
var col2_sum = 0;
a = [[1,2],[3,4],[5,6],[7,8]];
a.forEach(function(element, index, array) { col1_sum += element[0]; col2_sum += element[1]; });
alert(col1_sum);
alert(col2_sum);
I made a simple jsfiddle from your underscore reduce code, and it seems to be working fine: http://jsfiddle.net/PdL5P/
var a = [[1,2],[3,4],[5,6],[7,8]]
var col1_sum = _.reduce(a, function(memo,obj){ return memo + parseFloat(obj[0]); }, 0 );
$("#sum").html(col1_sum)
Are you sure that "a" is defined at that point of your code?
You can also kick it new school:
var sumColumnJS = function sumColumnJS(array, col) {
var sum = 0;
array.forEach(function (value, index, array) {
sum += value[col];
});
return sum;
};
or use the _.each array iterator:
sumColumn_ = function sumColumn_(array, col) {
var sum = 0;
_.each(a, function (item) {
sum += item[col];
});
return sum;
};
Working demo: http://jsfiddle.net/HTqvf/
Simple iteration, as in any traditional language
var col1_sum = 0, col2_sum = 0, row;
for (row in a)
{
col1_sum += a[row][0];
cos2_sum += a[row][1];
}
I would do this.
a = [[1,2],[3,4],[5,6],[7,8]]
col1_sum = _.sum(_.map(a,0))
col2_sum = _.sum(_.map(a,1))
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