Get the array key with the highest value in javascript - javascript

I have a array like
arr[1] = 234;
arr[2] = 345;
...
arr[40] = 126;
How can I get the index of the element with the highest value without reiterating the array?

You can apply Math.max and pass the array as its arguments-
arr.indexOf(Math.max.apply(window,arr))
But now Math.max is doing the iterating, just as sort would do.
Somebody has to look at each item in an unsorted array...

With jQuery, is as simple as:
// Get the max value from the array
maxValue = Math.max.apply(this, arr);
// Get the index of the max value, through the built in function inArray
$.inArray(maxValue,arr);

If the array is not ordered you cannot do this without iterating.

Get the array key with the highest value in javascript
var cars = ["Saab", "Volvo", "BMW"];
var max_car_result = cars[cars.length-1];
alert(max_car_result);

Try this:
var max_index = -1;
var max_value = Number.MIN_VALUE;
for(var i = 0; i < arr.length; i++)
{
if(arr[i] > max_value)
{
max_value = arr[i];
max_index = i;
}
}

You could use a function to set the variable. And keep track of the max in that function. Here's a quick example without type checking, testing, or support for removing a value.
Array.prototype.maxValue = null;
Array.prototype.setIndex = function(index, value){
this[index] = value;
if (value > this.maxValue || this.maxValue == null)
this.maxValue = value;
}
var arr = new Array();
arr.setIndex(0, 234);
arr.setIndex(1, 500);
arr.setIndex(2, -5);
var maxValue = arr.maxValue;
Obviously this is nicer if you're currently setting items like this:
var arr = new Array();
arr[0] = 1;
arr[1] = 500;
arr[2] = 2;
Rather than this:
var arr = { 1, 500, 2 };
The downside is its not natural and requires you to use function to get the correct results.

Keep the array sorted or use a heap.
Otherwise iterate. Even if you found some trick to do it it would still require iterating underneath so why not iterate?
If it seems like too much code, put it in a separate routine.

Two solution: to sort descending order and get the first element or:
function bigger(array) {
if (array.length < 1) {
return -1;
}
bigger = 0;
for(var i=1; i<array.length;i++ ) {
if(array[i] > array[bigger]) {
bigger = i;
}
}
return bigger;
}
you cold optimize using two variables, one for the position and other for the content.

Either you will have iteration somewhere (in your code or in JQuery.each()) or you can define something like this:
Array.prototype.mpush = function(v)
{
var maxv = this.maxValue || Number.MIN_VALUE;
if( v > maxv ) { this.maxValue = v; this.maxIndex = this.length; }
this.push(v);
}
and use that arr.mpush(v) to populate your array. In this case the array will have maxIndex property.

Is old question but here is an my simple emulation of PHP script max() made in javascript:
function max(array){
if(Object.prototype.toString.call( array ) === '[object Array]'){
return array[(array.length-1)];
}
else return 0;
}
This return value of last key in array or 0 if nothing found.
Maby someone helps.
You can use it like:
var array = ['bananaman','spiderman','ironman','superman','batman','manman'];
var getLast = max(array);
if(getLast !== 0)
alert(getLast); // manman

Related

Jquery/Javascript removing entry from array with highest property value

I have a nice riddle that I would like to see solved. There might be a better way of doing this and i am open for idea's.
I am trying to write an undo function for a canvas drawing app.
I have the following object, within it an array with their own objects with three properties.
var allDamages= {};
allDamages['scratch'] = [];
allDamages['scratch'].push({"x":4,"y":6,"index":1});
allDamages['scratch'].push({"x":3,"y":3,"index":2});
allDamages['scratch'].push({"x":9,"y":9,"index":3});
allDamages['scratch'].push({"x":19,"y":39,"index":4});
allDamages['dent'] = [];
allDamages['dent'].push({"x":59,"y":69,"index":5});
allDamages['dent'].push({"x":59,"y":69,"index":9});
allDamages['dent'].push({"x":39,"y":19,"index":6});
allDamages['rip'] = [];
allDamages['rip'].push({"x":20,"y":22,"index":7});
allDamages['rip'].push({"x":100,"y":56,"index":8});
I want to remove the last entry from this array. I want to do this by the property 'index'.
So I need to somehow find the entry which has the highest value of the property 'index' and then remove it from the array. What is the best way in doing this?
Greetings,
Robert
allDamages.scratch.length -1 returns the last index for that array.
Edit:
allDamages.scratch.slice(-1).pop() returns the last array item.
And if you just want to remove the last item in your array you should (like Givi said) use the pop() method on a sorted array like so:
allDamages['scratch'].pop()
Edit2:
Because the question wasn't clear for me. This is my final shot at the problem.
var allDamagesInOneArray = [];
for(array in allDamages){
allDamagesInOneArray.concat(array);//Assuming every key is an array
}
allDamagesInOneArray.sort(function(a,b){
return a.index - b.index;
});
var lastObj = allDamagesInOneArray.slice(-1).pop(); //element with latest index
I think you should create an object that save three your properties. After that you create a stack for undo. Like this:
function yourObject(x,y,index){
this.x = x; this.y = y; this.index = index;
}
var yourStack = new Array();
yourStack.push(new yourObject(4, 6, 1));
If the highest index in an array is always the last element of the array:
allDamages.scratch = allDamages.scratch.slice(0, allDamages.scratch.length - 1);
This removes the last element of the array
If index is not incrementing or if you always want to remove the latest index, no matter in which of the damages arrays it is (as I'd guess) you can use this function:
var undo = function(input){
var max= 0;
var undoType = "";
var undoIndex = 0;
for( var type in input ) {
// type: string
var locations = input[type];
// locations: array
// find the location of the heighest index property.
for( var i = 0; i < locations.length; i++ ) {
if( locations[i]["index"] > max) {
max = locations[i]["index"] ;
undoType = type;
undoIndex = index;
}
}
}
var output = input[type].splice(undoIndex, 1);
return output;
}
This should remove the element with the largest "index" property from your damage array.
First off, store a counter for highest index property found in the objects, and the index of that object within the scratch array.
var highestIndex = -Infinity;
var indexInArray
Then if you're using jQuery:
$.each( allDamages.scratch, function highestIndex( index, object ){
if( object.index > highestIndex ){
highestIndex = object.index;
indexInArray = index;
}
} );
Or, if not:
for( var indexCounter = 0, indexCounter < allDamages.scratch, indexCounter++ ){
if( allDamanges.scratch[ indexCounter ].index > highestIndex ){
highestIndex = allDamages.scratch[ indexCounter ].index;
indexInArray = indexCounter;
}
};
Try:
var allDamages= {};
allDamages['scratch'] = [];
allDamages['scratch'].push({"x":4,"y":6,"index":1});
allDamages['scratch'].push({"x":3,"y":3,"index":2});
allDamages['scratch'].push({"x":9,"y":9,"index":3});
allDamages['scratch'].push({"x":19,"y":39,"index":4});
allDamages['dent'] = [];
allDamages['dent'].push({"x":59,"y":69,"index":5});
allDamages['dent'].push({"x":59,"y":69,"index":9});
allDamages['dent'].push({"x":39,"y":19,"index":6});
allDamages['rip'] = [];
allDamages['rip'].push({"x":20,"y":22,"index":7});
allDamages['rip'].push({"x":100,"y":56,"index":8});
var index;
var cnt = 0;
var val;
$.each(allDamages,function(k,v){
if(cnt == 0){
index = highest(v); //get highest value from each object of allDamages
val = k;
}
else{
if(highest(v) > index){
index = highest(v);
val = k;
}
}
cnt++;
});
console.log("highest : "+index+": "+val);
var len = allDamages[val].length;
for(var i=0;i<len;i++){
if(allDamages[val][i].index == index){
allDamages[val].splice(i,1); //remove object having highest value
break;
}
}
console.log(allDamages);
function highest(ary) {
var high = ary[0].index;
var len = ary.length;
if(len > 0){
for(var i=0;i<len;i++){
if(ary[i].index > high){
high = ary[i].index;
}
}
}
return high;
}
DEMO here.
I've simplified my array to:
allDamages.push({"x":39,"y":19,"index":6,"type":'dent'});
That way i can use .pop() function in a normal way.
Thank you all for the quick response!!!

Loop through and compare javascript objects

I have two arrays which are created from the inputs of a user like so:
var impArray = [];
$('[id^=imp]').on('change', function(){
var value = $(this).val();
var name = ($(this).attr('name').replace('imp-',''))
impArray[name] = value;
console.log(impArray);
})
var assessArray= [];
$('[id^=assess]').on('change', function(){
var value = $(this).val();
var name = ($(this).attr('name').replace('assess-',''))
assessArray[name] = value;
console.log(assessArray);
})
These create arrays like
assessAray
1-1: 10
1-2: 15
1-3: 9
impArray
1-1: 6
1-2: 14
1-3: 2
I then need to do a simple calculation with the matching keys like:
$('#comp-1-1').val(impArray['1-1'] / assessArray['1-1'] * 100);
Obviously I can't do this with every single one, so,
Question: How can I loop through the arrays and compare them based on keys then do something with their values?
Technically, you are working with JavaScript objects, not arrays. Your variable declarations should actually be:
var impArray = {};
var assessArray = {};
Once you have the correct variable declarations, you can use jQuery.each to iterate through keys (not indexes):
$.each(impArray, function(key, value){
$('#comp-'+key).val(assessArray[key]/value*100);
});
Try using $.each(), like:
$.each(impArray, function(i, v){
$('#comp-'+i).val(v/assessArray[i]*100);
});
Does this help you?
$.each(impArray, function(index, value){
var result = assessArray[index] / value * 100;
$('#comp-1-'+index).val(result);
});
If both arrays will always be the same length and have the object property at the same index, this should work:
http://jsfiddle.net/9DBuD/
assessArray = [{'1-1':'10'},{'1-2':'15'},{'1-3':'9'}];
impArray = [{'1-1':'6'},{'1-2':'14'},{'1-3':'2'}];
for(var i=0;i<assessArray.length;i++){
for(var prop in assessArray[i]){
for(var property in impArray[i]){
if(prop == property){
$('#comp-'+prop).val(impArray[i][property]/assessArray[i][prop]*100)
}
}
}
}
Edit
This modified fiddle and code should produce the same results even if the array indexes and sizes do not match:
http://jsfiddle.net/9DBuD/1/
Array.prototype.indexOfProp = function (property) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i][property]!=undefined) return i;
}
return -1;
}
assessArray = [{'1-2':'15'},{'1-3':'9'},{'1-1':'10'},{'1-4':'10'}];
impArray = [{'1-1':'6'},{'1-3':'2'},{'1-2':'14'}];
for(var i=0;i<assessArray.length;i++){
for(var prop in assessArray[i]){
var index = impArray.indexOfProp(prop)
if(index!=-1){
$('#comp-'+prop).val(impArray[index][prop]/assessArray[i][prop]*100)
}
}
}

Count how many strings in an array have duplicates in the same array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/

Remove duplicate element pairs from multidimensional array

I have an array that looks like this:
1. coordinates = [ [16.343345, 35.123523],
2. [14.325423, 34.632723],
3. [15.231512, 35.426914],
4. [16.343345, 35.123523],
5. [15.231512, 32.426914] ]
The latitude on line 5 is the same as on line 3, but they have different longitudes and are therefore not duplicates.
Both the latitude and longitude are the same on line 3 and 6, and are therefore duplicates and one should be removed.
The difficulty in this question that different arrays never compare equal even if they contain same values. Therefore direct comparison methods, like indexOf won't work.
The following pattern might be useful to solve this. Write a function (or use a built-in one) that converts arrays to scalar values and checks if these values are unique in a set.
uniq = function(items, key) {
var set = {};
return items.filter(function(item) {
var k = key ? key.apply(item) : item;
return k in set ? false : set[k] = true;
})
}
where key is a "hash" function that convert items (whatever they are) to comparable scalar values. In your particular example, it seems to be enough just to apply Array.join to arrays:
uniqueCoords = uniq(coordinates, [].join)
You can use standard javascript function splice for this.
for(var i = 0; i < coordinates.length; i++) {
for(var j = i + 1; j < coordinates.length; ) {
if(coordinates[i][0] == coordinates[j][0] && coordinates[i][1] == coordinates[j][1])
// Found the same. Remove it.
coordinates.splice(j, 1);
else
// No match. Go ahead.
j++;
}
}
However, if you have thousands of points it will work slowly, than you need to consider to sort values at first, then remove duplicates in one loop.
I rewrote the answer from thg435 (It does not allow me to post comments) and prototype it also using jQuery instead, so this will work on all browsers using it (Even IE7)
Array.prototype.uniq = function (key) {
var set = {};
return $.grep(this, function (item) {
var k = key
? key.apply(item)
: item;
return k in set
? false
: set[k] = true;
});
}
You can use it like:
arr = arr.uniq([].join);
If you are not on Safari this single liner could do the job
var arr = [[16.343345, 35.123523],
[14.325423, 34.632723],
[15.231512, 35.426914],
[16.343345, 35.123523],
[15.231512, 32.426914]],
lut = {},
red = arr.filter(a => lut[a] ? false : lut[a] = true);
document.write("<pre>" + JSON.stringify(red,null,2) + "</pre>");
It might be simpler to create another array keeping only unique coordinate pairs
var uniqueCoors = [];
var doneCoors = [];
for(var x = 0; x < coordinates.length; x++) {
var coorStr = coordinates[x].toString();
if(doneCoors.indexOf(coorStr) != -1) {
// coordinate already exist, ignore
continue;
}
doneCoors.push(coorStr);
uniqueCoors.push(coordinates[x]);
}
function sortCoordinates(arr){
var obj = {};
for(var i = 0, l = arr.length; i < l; i++){
var el = arr[i];
var lat = el[0];
var lng = el[1];
if(!obj[lat + lng]){
obj[lat + lng] = [lat, lng];
}
}
var out = [];
for(p in obj){
out.push([obj[p][0], obj[p][1]]);
}
return out;
}
I am not sure about coordinates[][] dataType. Make the comparison accordingly.
var dubJRows= new Array();
for(int i = 0; i < coordinates.length -2; i++){
for(int j = i+1; j < coordinates.length -1; j++){
if (i != j && chk_dubJRows_not_contains(j)) {
innerArray1 [1][1] = coordinates[i];
innerArray2 [1][1] = coordinates[j];
if ( innerArray1 [1][0] == innerArray2[1][0]
&& innerArray1[1][1] == innerArray2[1][1]) {
dubJRows.push(j);
}
}
}
}
//REMOVE ALL dubJRows from coordinates.

Get max and min value from array in JavaScript

I am creating the following array from data attributes and I need to be able to grab the highest and lowest value from it so I can pass it to another function later on.
var allProducts = $(products).children("li");
prices = []
$(allProducts).each(function () {
var price = parseFloat($(this).data('price'));
prices[price] = price;
});
console.log(prices[0]) <!-- this returns undefined
My list items look like this (I have cut down for readability):
<li data-price="29.97">Product</li>
<li data-price="31.00">Product</li>
<li data-price="19.38">Product</li>
<li data-price="20.00">Product</li>
A quick console.log on prices shows me my array which appears to be sorted so I could grab the first and last element I assume, but presently the names and values in the array are the same so whenever I try and do a prices[0], I get undefined
[]
19.38 19.38
20.00 20.00
29.97 29.97
31.00 31.00
Got a feeling this is a stupidly easy question, so please be kind :)
To get min/max value in array, you can use:
var _array = [1,3,2];
Math.max.apply(Math,_array); // 3
Math.min.apply(Math,_array); // 1
Why not store it as an array of prices instead of object?
prices = []
$(allProducts).each(function () {
var price = parseFloat($(this).data('price'));
prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array
That way you can just
prices[0]; // cheapest
prices[prices.length - 1]; // most expensive
Note that you can do shift() and pop() to get min and max price respectively, but it will take off the price from the array.
Even better alternative is to use Sergei solution below, by using Math.max and min respectively.
EDIT:
I realized that this would be wrong if you have something like [11.5, 3.1, 3.5, 3.7] as 11.5 is treated as a string, and would come before the 3.x in dictionary order, you need to pass in custom sort function to make sure they are indeed treated as float:
prices.sort(function(a, b) { return a - b });
Instead of .each, another (perhaps more concise) approach to getting all those prices might be:
var prices = $(products).children("li").map(function() {
return $(this).prop("data-price");
}).get();
additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:
prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });
then use Sergey's solution above:
var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);
if you have "scattered" (not inside an array) values you can use:
var max_value = Math.max(val1, val2, val3, val4, val5);
arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);
use this and it works on both the static arrays and dynamically generated arrays.
var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );
I had the issue when I use trying to find max value from code below
$('#myTabs').find('li.active').prevAll().andSelf().each(function () {
newGetWidthOfEachTab.push(parseInt($(this).outerWidth()));
});
for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
newWidthOfEachTabTotal += newGetWidthOfEachTab[i];
newGetWidthOfEachTabArr.push(parseInt(newWidthOfEachTabTotal));
}
getMaxValue = Math.max.apply(Math, array);
I was getting 'NAN' when I use
var max_value = Math.max(12, 21, 23, 2323, 23);
with my code
Find largest and smallest number in an array with lodash.
var array = [1, 3, 2];
var func = _.over(Math.max, Math.min);
var [max, min] = func(...array);
// => [3, 1]
console.log(max);
console.log(min);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
If there exists requirement to find solution without using Math library, or Sorting logic, the below solutions might help.
To find the max value in javascript,
var max = -Infinity;
for (var i = 0; i < arr.length; ++i) {
if (arr[i] < max) continue;
if (arr[i] > max) {
max = arr[i];
}
}
return max;
To find the min value,
var min = +Infinity;
for (var i = 0; i < arr.length; ++i) {
if (arr[i] > min) continue;
if (arr[i] < min) {
min = arr[i];
}
}
return min;
To find all the occurrences of max values, (alter the comparisons to get all min values)
var max = -Infinity, result = [];
for (var i = 0; i < arr.length; ++i) {
if (arr[i] < max) continue;
if (arr[i] > max) {
result = [];
max = arr[i];
}
result.push(max);
}
return result; // return result.length to return the number of occurrences of max values.

Categories