return biggest/highest object from jquery elements - javascript

Howdey!
Let's take a look at the following jQuery function:
$.fn.getMax = function() {
return this.height(Math.max.apply(this, $(this).map(function(i, e) {
return $(e).height();
}).get()));
};
It returns and sets the heighest height for all selectors. But what is, if you want to return the object (not the height) with the heighest value?
So if you call the function like this:
$(selector).getMax().css({backgroundColor: "indigo"});
...how the element with the heighest height gets the backgroundColor?
UPDATE
I've managed it now with $.makeArray, as Amareswar said it.
$.fn.getMax = function(prop) {
var max = $.makeArray($(this)).sort(function(a, b) {
return (parseInt($(b).css(prop), 10) || 1) - (parseInt($(a).css(prop), 10) || 1);
}).shift();
return $(max);
};
Cheers!

Try this:
$.fn.getMax = function() {
/* create array of heights*/
var heights = $(this).map(function(i, e) {
return $(e).height();
}).get();
/* get max height*/
var max = Math.max.apply(this, heights);
/* get index of max in array*/
var pos = $.inArray(max, heights)
/* return element with proper index*/
return this.eq(pos);
};
DEMO: http://jsfiddle.net/tTuE7/
EDIT : assumes you only want one element returned

Related

Function not returning the volume value

i was wondering why this function its not working as far as my understanding goes(newbie) when invoking i should have the value[0] and [1] in order to get the result that i am looking for but i have tried in the browser and in console.log and i am not getting the [1] return value as expected.
function getSize(width, height, depth) {
var area = width * height;
var volume = width * height * depth;
var sizes = [area, volume];
alert(area);
}
var areaOne = getSize(3, 2, 1)[0];
var volumeOne = getSize(2, 1, 5)[1];
Here you are missing return.
A function should always return value.
function getSize(width,height,depth){
var area =width * height;
var volume=width*height*depth;
var sizes=[area,volume];
//alert(area);
return area;
}
var areaOne=getSize(3,2,1)[0];
var volumeOne=getSize(2,1,5)[1];
console.log(volumeOne)
You should return the value form you function in order to retrieve the values.
function getSize(width,height,depth){
var area =width * height;
var volume=width*height*depth;
var sizes=[area,volume];
return [volume, area]; // you should reuren the value in order to get it
}
var areaOne=getSize(3,2,1)[0];
var volumeOne=getSize(2,1,5)[1];
console.log(areaOne, volumeOne);
Your function doesn't have a return parameter, in order to assign functions output (in this case sizes[] array) your function needs to return that value, just add return sizes; at the end of your function definition.

How to Sort an Array in javascript by calculated fields like percentage

How do I sort an array of an object by a calculated field of object properties like percentage of 2 properties of an object like below
myArray.sort( function(a,b){
var firstPer = calculatePercent(a[factor],a.Total_Records);
var secPer = calculatePercent(b[factor],b.Total_Records);
if(dir ==='asc')
return firstPer < secPer ? something : something
} )
You just need to return a number:
myArray.sort(function(a,b) {
var firstPer = calculatePercent(a[factor], a.Total_Records);
var secPer = calculatePercent(b[factor], b.Total_Records);
if (dir === 'asc') {
return firstPer - secPer;
}
return secPer - firstPer;
}

How discover the element with the max font-size

I'm trying to answer the call of a function based on comparison of THIS element (keyword) font-size with font-sizes of other elements:
This is inside a prototype:
The self.settings.same is an array with the other elements.
self.settings.same.forEach(function (item) {
var me = parseInt(self.element.css('fontSize').substring(-1, 2), 10);
var other = parseInt(item.css('fontSize').substring(-1, 2), 10);
if (other > me) {
return false;
}
return true;
});
I want return false if the others elements have the font-size bigger then the current element, but this is not working because it makes the loop only once, so the comparison occurs only once.
If you can return false only when all others elements are bigger than me, then this should work.
self.settings.same.forEach(function (item) {
var me = parseInt(self.element.css('fontSize').substring(-1, 2), 10);
var other = parseInt(item.css('fontSize').substring(-1, 2), 10);
if (other < me) {
return true;
}
});
return false;

Manipulating JSON with LoDash

I've just started working with Lodash, and am trying to average out any value (at the lowest level) that's an array. No matter what I try, the original JSON persists.
Do I need to build a brand new object and push everything into it? Why can't I simply manipulate it like I would an array?
function averageIt(mtcs) {
function jsonAvg(dataSet) {
function avg(elmt) {
var sum = 0;
for( var i = 0; elmt[i]; i++ ){
sum += parseInt( elmt[i], 10 );
}
return Math.round(sum/elmt.length * 100) / 100;
}
_.forEach(dataSet.json, function(day) {
_.mapValues(day, function(n) {
return _.isArray(n) ? avg(n) : n;
});
});
console.log("JSON Averaged:", dataSet.json);
return dataSet;
}
_.forIn(mtcs.dataSets, function(set) {
set = jsonAvg(set);
});
console.log("Averaged Metrics:", mtcs);
return mtcs;
}
Regards
- - - Really Confused "Programmer"
If I understand it correctly, when you use _.mapValues is where the avg function is applied. But as you are using a map function, the result you set in the return is not stored anywhere, and the dataSet.json remains the same. You could do this:
_.each(dataSet.json, function(day, index) {
dataSet.json[index] = _.mapValues(day, function(n) {
return _.isArray(n) ? avg(n) : n;
});
});
Supposing that dataSet.json is an array. If it is an object, you should not apply an each to it, but do something like Object.keys(dataSet.json) to convert its properties to an array.

jQuery min/max property from array of elements

Is there a simple way to find the min/max property from an array of elements in jQuery?
I constantly find myself dynamically resizing groups of elements based on the minimum and maximum counterparts. Most of the time this pertains to the width and/or height of an element but I'm sure this could be applied to any property of an element.
I usually do something like this:
var maxWidth = 0;
$('img').each(function(index){
if ($(this).width() > maxWidth)
{
maxWidth = $(this).width();
}
});
But it seems like you should be able to do something like this:
var maxWidth = $('img').max('width');
Does this functionality exist in jQuery or can someone explain how to create a basic plugin that does this?
Thanks!
Use Fast JavaScript Max/Min - John Resig
Example with three logos of google, yahoo and bing.
HTML
<img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" alt="Google Logo" /><br/>
<img src="http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png" alt="Yahoo Logo" /><br/>
<img src="http://www.bing.com/fd/s/a/h1.png" alt="Bing Logo" />
Javascript
$(document).ready(function(){
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};
// Function to get the Min value in Array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
//updated as per Sime Vidas comment.
var widths= $('img').map(function() {
return $(this).width();
}).get();
alert("Max Width: " + Array.max(widths));
alert("Min Width: " + Array.min(widths));
});
P.S: jsfiddle here
You can use apply outside the context of OO, no need to extend the prototype:
var maxHeight = Math.max.apply( null,
$('img').map(function(){ return $(this).height(); }).get() );
I like the elegant solution posted as a .map() example in the jQuery docs on how to equalize div heights. I basically adapted it to work with widths and made a demo.
$.fn.limitWidth = function(max){
var limit = (max) ? 'max' : 'min';
return this.width( Math[limit].apply(this, $(this).map(function(i,e){
return $(e).width();
}).get() ) );
};
// Use the function above as follows
$('.max-width').limitWidth(true); // true flag means set to max
$('.min-width').limitWidth(); // no flag/false flag means set to min
Take a look at the calculation plugin, maybe it can help you with your problems.
They offer a number of math functions, like min, max and avg on DOM-elements.
Examples:
$("input[name^='min']").min();
$("input[name^='max']").max();
Rolled up as a plugin to return min-max of width and height:
// Functions to get the Min & Max value in Array
if (!Array.min) { Array.min = function( array ){return Math.min.apply( Math, array )} }
if (!Array.max) { Array.max = function( array ){return Math.max.apply( Math, array )} }
(function( $ ){ // Standard jQuery closure to hide '$' from other libraries.
// jQuery plug-in to get the min and max widths of a set of elements
$.fn.dimensionsMinMax = function(whnx) {
/*
################################################################################
Name
====
dimensionsMinMax(whnx) - jQuery plug-in to get min & max width & height
Parameters
==========
whnx - A 4-element array to receive the min and max values of the elements:
whnx[0] = minimum width;
whnx[1] = maximum width;
whnx[2] = minimum height;
whnx[3] = maximum height.
Returns
=======
this - so it can be "chained".
Example
=======
var minmax = new Array(4);
var number_of_images = $('img').dimensionsMinMax(minmax).class('abc').length;
console.log('number of images = ', number_of_images);
console.log('width range = ', minmax[0], ' to ', minmax[1]);
console.log('height range = ', minmax[2], ' to ', minmax[3]);
################################################################################
*/
var widths = new Array(this.length);
var heights = new Array(this.length);
this.each(function(i){
$this = $(this);
widths[i] = $this.width();
heights[i] = $this.height();
});
whnx[0] = Array.min( widths);
whnx[1] = Array.max( widths);
whnx[2] = Array.min(heights);
whnx[3] = Array.max(heights);
return this;
}
})( jQuery ); // End of standard jQuery closure.
I wrote a simple plugin to do exactly this - see gregbrown.co.nz/code/jquery-aggregate . With it installed, you could do:
var maxWidth = $('img').aggregate('width', 'max');
You can use native "sort" function to have more control over which elements are compared
Array.prototype.deepMax = function(comparator){
if(typeof comparator === 'function'){
var sorted = this.slice(0).sort(comparator);
return sorted[sort.length - 1];
}
return Math.max.apply(Math, this);
};
and you can call it like
var maxWidth = $('img').deepMax(function(a, b){
//-1 if a < b; +1 otherwise
return $(a).width() - $(b).width();
});
OR
you can use _.max of Underscore which is can be implemented like...
Array.prototype.max = function(iterator){
if(!iterator && obj[0] === +obj[0])
return Math.max.apply(Math, this);
var result = -Infinity, lastComputed = -Infinity;
this.forEach(function(value, index){
var computed = iterator ? iterator(value, index, this) : value;
computed > lastComputed && (result = value, lastComputed = computed);
});
return result;
};
var maxWidth = $('img').max(function(val){ return $(val).width();});
The Plugins/Authoring page actually has an example for determining the tallest element.
It's basically what you have here, just rolled into a plugin for easy access. Maybe you could appropriate it for your uses.

Categories

Resources