How to get the property with the largest number? - javascript

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/

Related

JavaScript: find Object with highest summed values from Array

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);

String to array - split returning NaN value | Javascript

I want to convert a string into an array. that works only with number value. in the following example the "border_color & border_style keys" returning NaN as value.
var str ="margin_top=5&margin_bottom=5&border_color=#dfdfdf&border_style=solid";
strToArray(str);
function strToArray(str){
str = str.replace(/\(|\)/g,'');
var arr = str.split('&');
var obj = {};
for (var i = 0; i < arr.length; i++) {
var singleArr = arr[i].trim().split('=');
var name = singleArr[0];
var value = singleArr[1]-0;
if (obj[name] === undefined) {
obj[name] = value;
}
alert(name+': '+value);
}
return obj;
}
The NaNs are comming from trying to convert the non-numeric values into numbers (ie, "#dfdfdf" and "solid"). Before trying to convert to numbers, check if the value string is valid or not using isNaN:
var value = singleArr[1]; // don't convert yet
if (obj[name] === undefined) {
obj[name] = isNaN(value)? value: +value; // if value is not a valid number, then keep it as it is (a string). Otherwise, convert it to a number (using unary + which is shorter than substracting 0)
}
Working example:
var str ="margin_top=5&margin_bottom=5&border_color=#dfdfdf&border_style=solid";
strToArray(str);
function strToArray(str){
str = str.replace(/\(|\)/g,'');
var arr = str.split('&');
var obj = {};
for (var i = 0; i < arr.length; i++) {
var singleArr = arr[i].trim().split('=');
var name = singleArr[0];
var value = singleArr[1];
if (obj[name] === undefined) {
obj[name] = isNaN(value)? value: +value;
}
alert(name+': '+value);
}
return obj;
}
Not really sure the way you want to return, but you can use: Object.values()
var str ="margin_top=5&margin_bottom=5&border_color=#dfdfdf&border_style=solid";
strToArray(str);
function strToArray(str){
str = str.replace(/\(|\)/g,'');
var arr = str.split('&');
var keys = []
var values = []
var obj = {};
for (var i = 0; i < arr.length; i++) {
var singleArr = arr[i].trim().split('=');
keys.push(Object.values(singleArr)[0])
values.push(Object.values(singleArr)[1])
}
alert(values)
alert(keys)
return obj;
}

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);

Modify an object to a new Array in Javascript

sorry, i m a beginner in javascript.
Can someone explain me how to modify this Object
{toto:[12,13,15],titi:[45,12,34]}
to this Array
newArray = [
{
toto:12,
titi:45
},{
toto:13,
titi:12
},{
toto:15,
titi:34}
]
Also, what the solution if the toto and titi doesn't have the same lenght
Thanks for support!
Here's how I did it. In this way, you don't need to know the names of the keys or the size of the array, but it does require a few loops.
obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];
// Find the longest array in your data set
longest = 0;
Object.keys(obj).forEach(function(key) {
if (obj[key].length > longest) {
longest = obj[key].length;
}
});
// Loop through the existing data set to create new objects
for (i = 0; i<longest; i++) {
newObject = {};
Object.keys(obj).forEach(function(key) {
newObject[key] = obj[key][i];
});
newArray.push(newObject);
}
console.log(newArray);
plnkr.co demo in the script.js file.
If you want to ignore keys that would have undefined values for uneven loops, you can add a conditional inside the forEach loop that creates a new object:
Object.keys(obj).forEach(function(key) {
if (obj[key][i] !== undefined) {
newObject[key] = obj[key][i];
}
});
Assuming lengths of toto and titi are the same:
Obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];
for (var k in Obj["toto"]) {
newArray.push({ toto:Obj["toto"][k],titi:Obj["titi"][k] });
}
Since the lengths of your inner arrays are equal, you should be able to simply loop through them and add a value from each array (for each iteration) into a new array :
// Your input
var input = {toto:[12,13,15],titi:[45,12,34]};
// An array to store your output
var output = [];
// Since your inner arrays are of equal size, you can loop through them
// as follows
for(var i = 0; i < input.toto.length; i++){
output.push({ toto: input.toto[i], titi: input.titi[i]});
}
You can see a working example of this here and what the output array looks like below :
A more generic approach
var object = { toto: [12, 13, 15], titi: [45, 12, 34] },
newArray = function (o) {
var keys = Object.keys(o),
l = keys.reduce(function (r, a) { return Math.max(r, o[a].length); }, 0),
i = 0,
t,
result = [];
while (i < l) {
t = {};
keys.forEach(function (k) { t[k] = o[k][i]; });
result.push(t);
i++;
}
return result;
}(object);
document.write('<pre>' + JSON.stringify(newArray, 0, 4) + '</pre>');

Sum all properties in object

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);

Categories

Resources