Find minimum value in javascript? - javascript

I want to print the minimum variable 'name' in JS. Currently it prints the minimaum value. I rather want the variable name. For eg:- In the current code, it gives me 4, but I want c. How can I do this?
<script>
function myFunction()
{
var a = 5;
var b =10;
var c = 4;
document.getElementById("demo").innerHTML=Math.min(a,b,c);
}
</script>

Working DEMO
This should do the trick:
//Push values to object
var age = {};
age.a = 5;
age.b = 10;
age.c = 4;
var min = Infinity, name;
// Loop through object to get min value and then find relevant name
for(var x in age) {
if( age[x] < min) {
min = age[x];
name = x;
}
}
console.log ( 'property name is ' + name + ' and value is ' + min );

You could put your values in an array like
var values = [
{ name: 'a', value: 5 },
{ name: 'b', value: 10 },
{ name: 'c', value: 4 }
];
and then use the filter method with the hint from Ahmad's comment:
var min_value = Math.min.apply(null, values.map(function(item) {
return item.value;
}));
var min_name = values.filter(function (item) {
return item.value == min_value;
})[0].name;
See this fiddle for a working example.

Store the values in an array of objects. Each object will contain a name and value property. Then just iterate through the values and store the lowest.
var values = [
{
"name": "a",
"value": 5
},
{"name":"b",
"value":10
},
{
"name":"c",
"value":4
}
];
function min(arr){
var minValue = {};
for(var x = 0; x < arr.length; x++){
if(arr[x].value < minValue.value || !minValue.value){
minValue = arr[x];
}
}
return minValue.name;
};
document.getElementById("demo").innerHTML = min(values);
JS Fiddle: http://jsfiddle.net/AgMbW/

You can do this way:
var obj = {"names":["a","b","c"], "values":[5,10,4]}
var min = Math.min.apply( Math, obj["values"] );
var result = obj["names"][obj["values"].indexOf(min)];
document.getElementById("demo").innerHTML=result;
Here the fiddle: http://jsfiddle.net/eUcug/

Way 1 :
var x = 5;var getName = function(value){if(value === 5) return 'x'; else return null}
Way 2 :
NameValue.getName = function(value){for(i = 1;i<=2;i++){if(this["val" + i].value === value) {return this["val" + i].name;break;}console.log(this["val" + i]);}return null;}NameValue.val2 = {name : 'y',value : 1};NameValue.prototype.add({name : 'x',value : 10})
NameValue.getName(10); //return "x"
I hope you can understand how to find the variable name.

Related

Javascript : How group and sum values from multidimensional array

I have an array like this:
I would like to group and get the sum of each repetition like this:
AGE270: 9
AGE203: 5
AGE208: 9
...
AGEXXX: n
Simple solution using Array.prototype.reduce function:
// Replace arr with your actual array!
var arr = [
{ AGENDADOR: 'AGE270', TOTAL : 6},
{ AGENDADOR: 'AGE270', TOTAL : 3},
{ AGENDADOR: 'AGE203', TOTAL : 5},
{ AGENDADOR: 'AGE028', TOTAL : 9},
],
totals = arr.reduce(function (r, o) {
(r[o.AGENDADOR])? r[o.AGENDADOR] += o.TOTAL : r[o.AGENDADOR] = o.TOTAL;
return r;
}, {});
console.log(totals);
arr.reduce(callback, [initialValue])
initialValue
Optional. Value to use as the first argument to the first call of the callback.
Using lodash:
var data; // the data represented by your screenshot
var counts = _.chain(data)
.groupBy('AGENDADOR')
.map(_.size)
.value();
counts will now be an object like this:
{
"AGE270": 9,
"AGE203": 5,
// etc
}
var sum = {};
yourArray.forEach(function(item) {
if(sum[item.AGENDADOR] === undefined) {
sum[item.AGENDADOR] = 0;
}
sum[item.AGENDADOR] += item.TOTAL
});
With this code, you'll have the total corresponding to each key in the sum object. Something like this:
{
AGE270: 9,
AGE203: 5,
AGE208: 9
}
Try this out:
function( data ){
var outputObj = {} ;
for(var i=0;i < data.length; i++){
datum = data[i];
if(outputObj[datum.AGENDADOR])
outputObj[datum.AGENDADOR] += parseInt( datum.TOTAL) ;
else
outputObj[datum.AGENDADOR] = parseInt( datum.TOTAL);
}
return outputObj;
};
How about a simple map() function? Like this:
var t = YourArray;
var u = t.map(function (a, i) { var g = {}; g[a.AGENDADOR] = a.TOTAL; return g; });

Count the number of unique occurrences in an array that contain a specific string with Javascript

Here is my javascript array:
arr = ['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots'];
With Javascript, how can I count the total number of all unique values in the array that contain the string “dots”. So, for the above array the answer would be 3 (blue-dots, orange-dots, and red-dots).
var count = 0,
arr1 = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf('dots') !== -1) {
if (arr1.indexOf(arr[i]) === -1) {
count++;
arr1.push(arr[i]);
}
}
}
you check if a certain element contains 'dots', and if it does, you check if it is already in arr1, if not increment count and add element to arr1.
One way is to store element as key of an object, then get the count of the keys:
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
console.log(Object.keys(arr.reduce(function(o, x) {
if (x.indexOf('dots') != -1) {
o[x] = true;
}
return o
}, {})).length)
Try this something like this:
// Create a custom function
function countDots(array) {
var count = 0;
// Get and store each value, so they are not repeated if present.
var uniq_array = [];
array.forEach(function(value) {
if(uniq_array.indexOf(value) == -1) {
uniq_array.push(value);
// Add one to count if 'dots' word is present.
if(value.indexOf('dots') != -1) {
count += 1;
}
}
});
return count;
}
// This will print '3' on console
console.log( countDots(['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots']) );
From this question, I got the getUnique function.
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
then you can add a function that counts ocurrences of a string inside an array of strings:
function getOcurrencesInStrings(targetString, arrayOfStrings){
var ocurrencesCount = 0;
for(var i = 0, arrayOfStrings.length; i++){
if(arrayOfStrings[i].indexOf(targetString) > -1){
ocurrencesCount++;
}
}
return ocurrencesCount;
}
then you just:
getOcurrencesInStrings('dots', initialArray.getUnique())
This will return the number you want.
It's not the smallest piece of code, but It's highly reusable.
var uniqueHolder = {};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
arr.filter(function(item) {
return item.indexOf('dots') > -1;
})
.forEach(function(item) {
uniqueHolder[item] ? void(0) : uniqueHolder[item] = true;
});
console.log('Count: ' + Object.keys(uniqueHolder).length);
console.log('Values: ' + Object.keys(uniqueHolder));
Try this code,
arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
sample = [];
for (var i = 0; i < arr.length; i++) {
if ((arr[i].indexOf('dots') !== -1) && (sample.indexOf(arr[i]) === -1)){
sample.push(arr[i]);
}
}
alert(sample.length);
var arr = [ "blue-dots", "blue", "red-dots", "orange-dots", "blue-dots" ];
var fArr = []; // Empty array, which could replace arr after the filtering is done.
arr.forEach( function( v ) {
v.indexOf( "dots" ) > -1 && fArr.indexOf( v ) === -1 ? fArr.push( v ) : null;
// Filter if "dots" is in the string, and not already in the other array.
});
// Code for displaying result on page, not necessary to filter arr
document.querySelector( ".before" ).innerHTML = arr.join( ", " );
document.querySelector( ".after" ).innerHTML = fArr.join( ", " );
Before:
<pre class="before">
</pre>
After:
<pre class="after">
</pre>
To put this simply, it will loop through the array, and if dots is in the string, AND it doesn't already exist in fArr, it'll push it into fArr, otherwise it'll do nothing.
I'd separate the operations of string comparison and returning unique items, to make your code easier to test, read, and reuse.
var unique = function(a){
return a.length === 0 ? [] : [a[0]].concat(unique(a.filter(function(x){
return x !== a[0];
})));
};
var has = function(x){
return function(y){
return y.indexOf(x) !== -1;
};
};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
var uniquedots = unique(arr.filter(has('dots')));
console.log(uniquedots);
console.log(uniquedots.length);

How to get Math.min() to return the variable name instead of a number

I have five variables - organism.one, organism.two, and so on, up to five.
They're all equal to random numbers.
I'm trying to find the smallest of them, which I can do with Math.min().
However, Math.min returns the minimal number instead of the name of the variable which holds that minimum value.
Please help, I'm very new to JavaScript. This is my code so far:
runt = Math.min(organism.one, organism.two, organism.three, organism.four, organism.five);
console.log("The runt is " + runt);
Since you have an object with keys that contain numbers, you can use for ... in to iterate through them to find the smallest key:
var organism = {
one: 50,
two: 100,
three: 25,
four: 15,
five: 999
},
min = Infinity,
key;
for(var i in organism) {
if(organism[i] < min) {
min = organism[i];
key = i;
}
}
console.log(key); //four
My suggestion is use [].reduce
var objects = [{
name: 'one',
val: 13
},
{
name: 'two',
val: 12
},
{
name: 'three',
val: 11
}];
var minimum = objects.reduce(function(obj1, obj2){
return (obj1.val < obj2.val) ? obj1: obj2;
});
console.log(minimum.val)
No need for all these different functions, You're very close, you just need one loop to do it:
After you get the min, loop through the object to find a match:
JSBin Example
var organism = {
two: 2,
three: 3,
four: 4,
one: 1,
five: 5
};
var runt = Math.min(organism.one, organism.two, organism.three, organism.four, organism.five);
var lowest;
for (var org in organism) {
if (organism[org] === runt) {
lowest = org;
}
}
This should do it:
var lowestValsKey;
for(var key in organism){
if(!lowestValsKey){
lowestValsKey = key;
}
if(organism[key] < organism[lowestValsKey]){
lowestValsKey = key;
}
}
console.log(lowestValsKey);
If I understand what you're trying to do, perhaps you can use an object-oriented approach.
var organism = { "one" : someValue, "two" : someValue, "three" : someValue, "four": someValue, "five": someValue };
var min = null;
var minKey = null;
for( var key in organism ){
if( null === min ){
// we're at the beginning of the object, so assign min to that value.
min = organism[key];
minKey = key;
}
else if(( null !== min ) && ( organism[key] < min )){
min = organism[key];
minKey = key;
}
}
console.log( "The key with the min value is: " + key + " and the value is: " + organism[key] );
As you've noticed, Math.min only takes parameters and only returns a single number. There is no way to make it do what you are asking for it to do.
However, if I am reading your question correctly, what you are really asking is:
Can I pass an object to a function and get the key name of the lowest value?
If so, there is a way to do that.
var organism = {
one: 12,
two: 19,
three: -1,
four: 99,
five: 6
};
function findSmallestKey(obj) {
var smallestKey;
var smallestValue = Number.MAX_VALUE;
Object.keys(obj).forEach((key) => {
var val = obj[key];
if (val < smallestValue) {
smallestValue = val;
smallestKey = key;
}
});
return smallestKey;
}
var k = findSmallestKey(organism);
console.log('Smallest key is ', k);
You're probably not going to find the answer your looking for, because it's not possible. However, you can create your own function to do it.
function main(){
function getRandom(min,max){
return Math.floor(Math.random()*(max-min))+min;
}
var organism = {
one: getRandom(1,10),
two: getRandom(1,10),
three: getRandom(1,10),
four: getRandom(1,10),
five: getRandom(1,10),
};
function findMin(obj){
var keys = Object.keys(obj);
var min = {
name:keys[0],
val:obj[keys[0]]
};
keys.forEach((key)=>{
if (obj[key] < min.val)
min={name:key,val:obj[key]};
});
return min;
}
var min = findMin(organism);
document.getElementById('organisms').innerHTML = JSON.stringify(organism);
document.getElementById('min').innerHTML = ([min.name,min.val].join(': '));
}
<button onclick="main();">Run</button>
<pre id="organisms"></pre>
<div id="min"></div>

Javascript - Checking if a number is closer to 2 variables

I have 12 different numbers stored in variables, like this:
var span1 = 8.333333333;
var span2 = 16.66666667;
var span3 = 25;
var span4 = 33.33333333;
var span5 = 41.66666667;
var span6 = 50;
var span7 = 58.33333333;
var span8 = 66.66666667;
var span9 = 75;
var span10 = 83.33333333;
var span11 = 91.66666667;
var span12 = 100;
I have a function which compares a div's width to its parent's width and returns a value as a percentage (minus the % sign), for example, 48.5586. I'd like the function to check which of these span variables the result is closest to. For example, 48.5586 would return "span6" as it's closer to 50 than 41.666667.
Don't really know where to start with this one, any ideas?
Since each span is 8 1/3 % more than the previous one, which is just 100/12, you should be able to use a formula to work out which span class you need.
I worked out the following:
function spanClass(percentWidth) {
return 'span' + Math.round(percentWidth / (100/12));
}
This gives span6 for 48.5586.
The smallest difference can be found by taking the minimum of the absolute value of the difference between your input number and each variable's value.
That said, you should really use a proper data structure, like an object or an array, for mapping these strings to numbers.
Put the values in an array, then you can sort the array on the differece between the values. The smallest differece is first in the array, so that is the closest value:
var spans = [
{ span: 1, value: 8.333333333 },
{ span: 2, value: 16.66666667 },
{ span: 3, value: 25 },
{ span: 4, value: 33.33333333 },
{ span: 5, value: 41.66666667 },
{ span: 6, value: 50 },
{ span: 7, value: 58.33333333 },
{ span: 8, value: 66.66666667 },
{ span: 9, value: 75 },
{ span: 10, value: 83.33333333 },
{ span: 11, value: 91.66666667 },
{ span: 12, value: 100 }
];
var value = 48.5586;
spans.sort(function(x, y){
var a = Math.abs(value - x.value);
var b = Math.abs(value - y.value);
return a == b ? 0 : a < b ? -1 : 1;
});
alert(spans[0].span);
Demo: http://jsfiddle.net/Guffa/77Rf9/
Its better to have array. in my code also i am converting your variables to array and then processing. Eval is bad and should not be used
http://codebins.com/bin/4ldqp6b
var span1 = 8.333333333;
var span2 = 16.66666667;
var span3 = 25;
var span4 = 33.33333333;
var span5 = 41.66666667;
var span6 = 50;
var span7 = 58.33333333;
var span8 = 66.66666667;
var span9 = 75;
var span10 = 83.33333333;
var span11 = 91.66666667;
var span12 = 100;
var arr = [];
for (var i = 0; i < 12; i++) {
eval('arr[' + i + '] = span' + (i + 1));
}
function closestTo(arr, val) {
var closest = 10000,
ind = -1,
diff = 10000; // some random number
for (var i = 0; i < arr.length; i++) {
var tmp = Math.abs(val - arr[i]);
if (diff > tmp) {
diff = tmp;
closest = arr[i];
ind = i;
}
}
alert("Closesnt Number: " + closest + "\nClosest Index:" + ind + "\nclosest variable: span" + (ind + 1))
}
closestTo(arr, 50.12)
Implementation of a closest function in JavaScript. Moved all the spans into an object to make iterating over them easier. Just enumerate all the spans and keep the closest one.
var spans = {
span1: 8.333333333,
span2: 16.66666667,
span3: 25,
span4: 33.33333333,
span5: 41.66666667,
span6: 50,
span7: 58.33333333,
span8: 66.66666667,
span9: 75,
span10: 83.33333333,
span11: 91.66666667,
span12: 100
};
function closest(value) {
var delta
, lastMatch;
Object.keys(spans).forEach(function (span) {
var thisDelta;
if (!delta) {
lastMatch = span;
delta = Math.abs(value - spans[span]);
} else {
thisDelta = Math.abs(value - spans[span]);
if (thisDelta < delta) {
lastMatch = span;
delta = thisDelta;
}
}
});
return lastMatch;
}
var result = closest(48.5586);
console.log(result);
Here a working Codepen example.

Get the largest value from Json object with Javascript

This should be an easy one. I just cant figure it out.
How do I get the largest value from this piece of JSON with javascript.
{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}
The key and value I need is:
"two":35
as it is the highest
thanks
var jsonText = '{"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Happy with the service"}}'
var data = JSON.parse(jsonText).data
var maxProp = null
var maxValue = -1
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var value = data[prop]
if (value > maxValue) {
maxProp = prop
maxValue = value
}
}
}
If you have underscore:
var max_key = _.invert(data)[_.max(data)];
How this works:
var data = {one:21, two:35, three:24, four:2, five:18};
var inverted = _.invert(data); // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'};
var max = _.max(data); // 35
var max_key = inverted[max]; // {21:'one', 35:'two', 24:'three', 2:'four', 18:'five'}[35] => 'two'
This is my function for biggest key
function maxKey(a) {
var max, k; // don't set max=0, because keys may have values < 0
for (var key in a) { if (a.hasOwnProperty(key)) { max = parseInt(key); break; }} //get any key
for (var key in a) { if (a.hasOwnProperty(key)) { if((k = parseInt(key)) > max) max = k; }}
return max;
}
You can also iterate the object after you parse JSON .
var arr = jQuery.parseJSON('{"one":21,"two":35,"three":24,"four":2,"five":18}' );
var maxValue = 0;
for (key in arr)
{
if (arr[key] > maxValue)
{
maxValue = arr[key];
}
}
console.log(maxValue);

Categories