in javascript array find min max values [duplicate] - javascript

This question already has answers here:
Find the min/max element of an array in JavaScript
(58 answers)
Closed 9 years ago.
i have some arrays like this, the numbers in the array represents slots numbers
slots1 = {3,4,5,6}
slots2 = {1,2,3,4,5,6}
slots3 = {8,9,10}
i am finding whether the selected slots are successive or not.
first two arrays give correct min,max values.
but the third array is giving min = 10, max=9.
how to rectify it?
i am finding maximum value like this
for(var s=0;s<no_slots;s++)//finding maximum value of slots array
{
if(s == 0)
{
var slots_max = slots[s];
}
else
{
if(slots[s] > slots_max)
{
slots_max = slots[s];
}
}
}

Use the JS Math Object:
For the minimum: Math.min.apply(null,slots);
For the maximum: Math.max.apply(null,slots);

I am not sure why you function is not correctly working for your third case. You probably missed something silly like initialization or something similar to that.
As I have modified your some code and it is returning correctly. You can also make it shorter.
var slots = [8, 9, 10]
var slots_max = slots[0];
for (var s = 0; s < slots.length; s++) //finding maximum value of slots array
{
if (slots[s] > slots_max) {
slots_max = slots[s];
}
}
alert(slots_max);
Js Fiddle

You could instead try finding the minimum/maximum values using the Javascript Math library. This should return the correct result.
var min = Math.min.apply(null, slots3);
var max = Math.max.apply(null, slots3);
See this answer for more details.

Related

I am trying to create a function and I don't know how many inputs it will require, whats the best way to account for this? [duplicate]

This question already has answers here:
Pass unknown number of arguments into JavaScript function
(13 answers)
Closed 1 year ago.
function totalLength(thk, dim) {
var bendDeduction = 1.55 * thk;
var lengthMinusBend = dim - bendDeduction;
return lengthMinusBend;
}
This is the simplified version I have now. Basically, I want to be able to input several values for the dim input. currently, i am calculating the "dim" input outside of the function. The problem I am having is that I can't figure out a way to provide for the fact that the number of values I need to add to create the sum that is represented by the "dim" input will vary.
Also, this is currently only applicable for one bend. I want to be able to subtract the "bendDeduction" from each new input.
I am brand new to all of this, I am trying to wrap my head around all of this. I am thinking of some type of array and a for loop but I am so new to all of it I can't figure out exactly the way to write it. Thank you for any help.
use an "array" for the secod Argument :
function totalLength(thk, ...dim )
{
let bendDeduction = 1.55 * thk * dim.length
return dim.reduce((t,d)=>t+d) - bendDeduction;
}
console.log ( totalLength( 100, 200) )
console.log ( totalLength( 100, 200, 300) )
First, declare a helper function that calculates the sum of an array
Then you can use Rest Parameters to make the function accepts a variable number of arguments
function sumArray(arr) {
var res = 0;
for (var i = 0; i < arr.length; i++) {
res += arr[i];
}
return res;
}
function totalLength(thk, ...dim) {
var bendDeduction = 1.55 * thk;
var dimSum = sumArray(dim);
var lengthMinusBend = dimSum - bendDeduction;
return lengthMinusBend;
}
console.log(totalLength(100, 80, 60, 20));

How would be the sort for the beolw JS ,if i need to sort by {entry.heat)? [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 2 years ago.
I tried to retrieve data through a live server and display them through my local web application, the code to fetch the data by the user`s levels.
How I can sort them either by their levels or views entry.heat?
The levels or views entry.heat are values in the server and both are variables, so kindly check the below code in order to sort by entry.heat.
function(r){
var max = $('#limit').val();
if (r.data.video_info.length < max) max = r.data.video_info.length;
for (index = 0; index < max; index++) {
var entry = r.data.video_info[index];
var level = parseInt(entry.level);
if ((level > $('#min').val()) && (level < $('#max').val())) {
count++;
var h = '<div class="entry '+(entry.sex==0?'female':'male')+'"><img src="'+entry.smallcover+'">'+'<span>Heat:<span>'+entry.heat+'</span></h3>';
$('#main').append(h);
}
}
if ((current_page < 100) && (count < $('#limit').val() )) {
current_page++;
setTimeout(function(){
doSearch();
},0);
}
}
});
You make it hard to answer your question, since the source code is not formatted correctly. Also you say, you want to sort depending on the value of entry.heat but the code snippet doesn't show any reference to heat.
I'll try to answer though:
In order to sort an array in javascript you would like to use your_array.sort().
sort(arg: function) takes a function as argument. In this function you will be presented with two entries of you array. Your function shall tell which of two entries comes first. The function shall return a negative number, if entryB comes before entryA, a positive number if entryA comes before entryB or 0 if both entries are equal in case of the sorting property.
I assume in your case it would be:
your_array.sort((entryA, entryB) => {
return etryA.heat - entryB.heat;
});
or event shorter:
your_array.sort((a, b) => a.heat - b.heat);
Read on here: JavaScript: Array Sort

Add elements to 2D array in jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create a two dimensional array in JavaScript?
I want to push elements to 2D array,
My code is,
var results = [];
var resultstemp = [];
function bindlinks(aamt,id1) {
resultstemp=results;
imagesArray.push($("#image1").mapster("get"));
if(results.length==0)
{
results.push([id1]);
}
else
{
var ck=0;
var lng=results.length;
for (var i = 0; i < lng; i++) {
if(results[i]==id1)
{
ck=1;
results = jQuery.grep(results, function(value) {
return value != id1;
});
}
}
if(ck==0)
{
results.push(id1);
}
}
I want to push id as well as aamt to array. Here i am pushing only id to array. I am not sure about how to add aamt to second position in 2D array.
Help me please,
Thank you
Change the declaration as follows:
var results = new Array();
and change the push as follows:
results.push([id1,aamt]);
Hope it would help
The logic behind the method to push two separate values in the same array evenly is something like this:
var array = [];
function push(id1, aamt) {
for (var i= 0; i < 10; i++) {
if (i%2 == 0) {
array.push(id1);
}
else {
array.push(aamt);
}
}
}
push(10, 12);
console.log(array); // 10, 12, 10, 12.....
Take note i abstracted the code quite a bit, because for me was not too obvious what the code should have to do, but the principle is simple: use the modulo (%) operator to test if the value is odd or even. If odd add the first value if even add the second value.
Hope it helps.

Numeric sort of a stream that keeps alpha order when the number is the same

I tried a few of the regex sorts I found on SO, but I think they may not like the + symbol in the stream i'm needing to sort.
So I'm getting a data stream that looks like this (3 to 30 letters '+' 0 to 64000 number)
userString = "AAA+800|BBB+700|CCC+600|ZZZ+500|YYY+400|XXX+300|XXA+300|XXZ+300";
the output needs to be in the format:
array[0] = "XXA+300" // 300 being the lowest num and XXA being before XXX
array[...]
array[7] = "AAA+800"
I wish to order it from lowest num to highest num and reversed.
Here is my inefficient code. which loops 8x8 times. (my stream maybe 200 items long)
It works, but it looks messy. Can someone help me improve it so it uses less iterations?
var array = userString.split('|');
array.sort();
for(var i=0; i<len; i++) { // array2 contains just the numbers
bits = array[i].split('+');
array2[i] = bits[1];
}
array2.sort();
if(sort_order==2)
array2.reverse();
var c=0;
for(var a=0;a<len;a++) { // loop for creating array3 (the output)
for(var i=0; i<len ; i++) { // loop thru array to find matching score
bits = array[i].split('+');
if(bits[1] == array2[a]) { // found matching score
array3[c++] = bits[0]+'+'+bits[1]; // add to array3
array[i]='z+z'; // so cant rematch array position
}
}
}
array = array3;
Kind Regards
Please forgive the terse answer (and lack of testing), as I'm typing this on an iPhone.
var userArr = userString.split('|');
userArr.sort(function(a, b) {
var aArr = a.split('+'),
bArr = b.split('+'),
aLetters = aArr[0],
bLetters = bArr[0],
aNumbers = parseInt( aArr[1] ),
bNumbers = parseInt( bArr[1] );
if (aNumbers == bNumbers) {
return aLetters.localeCompare( bLetters );
}
return aNumbers - bNumbers;
/*
// Or, for reverse order:
return -(aNumbers - bNumbers);
// or if you prefer to expand your terms:
return -aNumbers + bNumbers;
*/
});
Basically we're splitting on | then doing a custom sort in which we split again on +. We convert the numbers to integers, then if they differ (e.g. 300 and 800) we compare them directly and return the result (because in that case the letters are moot). If they're the same, though (300 and 300) we compare the first parts (XXA and XXX) and return that result (assuming you want an ordinary alphabetical comparison). In this fashion the whole array is sorted.
I wasn't entirely sure what you meant by "and reversed" in your question, but hopefully this will get you started.
As you may've guessed this isn't totally optimal as we do split and parseInt on every element in every iteration, even if we already did in a previous iteration. This could be solved trivially by pre-processing the input, but with just 200 elements you probably won't see a huge performance hit.
Good luck!

alternatives for excessive for() looping in javascript

Situation
I'm currently writing a javascript widget that displays a random quote into a html element. the quotes are stored in a javascript array as well as how many times they've been displayed into the html element. A quote to be displayed cannot be the same quote as was previously displayed. Furthermore the chance for a quote to be selected is based on it's previous occurences in the html element. ( less occurrences should result in a higher chance compared to the other quotes to be selected for display.
Current solution
I've currently made it work ( with my severely lacking javascript knowledge ) by using a lot of looping through various arrays. while this currently works ( !! ) I find this solution rather expensive for what I want to achieve.
What I'm looking for
Alternative methods of removing an array element from an array, currently looping through the entire array to find the element I want removed and copy all other elements into a new array
Alternative method of calculating and selecting a element from an array based on it's occurence
Anything else you notice I should / could do different while still enforcing the stated business rules under Situation
The Code
var quoteElement = $("div#Quotes > q"),
quotes = [[" AAAAAAAAAAAA ", 1],
[" BBBBBBBBBBBB ", 1],
[" CCCCCCCCCCCC ", 1],
[" DDDDDDDDDDDD ", 1]],
fadeTimer = 600,
displayNewQuote = function () {
var currentQuote = quoteElement.text();
var eligibleQuotes = new Array();
var exclusionFound = false;
for (var i = 0; i < quotes.length; i++) {
var iteratedQuote = quotes[i];
if (exclusionFound === false) {
if (currentQuote == iteratedQuote[0].toString())
exclusionFound = true;
else
eligibleQuotes.push(iteratedQuote);
} else
eligibleQuotes.push(iteratedQuote);
}
eligibleQuotes.sort( function (current, next) {
return current[1] - next[1];
} );
var calculatePoint = eligibleQuotes[0][1];
var occurenceRelation = new Array();
var relationSum = 0;
for (var i = 0; i < eligibleQuotes.length; i++) {
if (i == 0)
occurenceRelation[i] = 1 / ((calculatePoint / calculatePoint) + (calculatePoint / eligibleQuotes[i+1][1]));
else
occurenceRelation[i] = occurenceRelation[0] * (calculatePoint / eligibleQuotes[i][1]);
relationSum = relationSum + (occurenceRelation[i] * 100);
}
var generatedNumber = Math.floor(relationSum * Math.random());
var newQuote;
for (var i = 0; i < occurenceRelation.length; i++) {
if (occurenceRelation[i] <= generatedNumber) {
newQuote = eligibleQuotes[i][0].toString();
i = occurenceRelation.length;
}
}
for (var i = 0; i < quotes.length; i++) {
var iteratedQuote = quotes[i][0].toString();
if (iteratedQuote == newQuote) {
quotes[i][1]++;
i = quotes.length;
}
}
quoteElement.stop(true, true)
.fadeOut(fadeTimer);
setTimeout( function () {
quoteElement.html(newQuote)
.fadeIn(fadeTimer);
}, fadeTimer);
}
if (quotes.length > 1)
setInterval(displayNewQuote, 10000);
Alternatives considered
Always chose the array element with the lowest occurence.
Decided against this as this would / could possibly reveal a too obvious pattern in the animation
combine several for loops to reduce the workload
Decided against this as this would make the code to esoteric, I'd probably wouldn't understand the code anymore next week
jsFiddle reference
http://jsfiddle.net/P5rk3/
Update
Rewrote my function with the techniques mentioned, while I fear that these techniques still loop through the entire array to find it's requirements, at least my code looks cleaner : )
References used after reading the answers here:
http://www.tutorialspoint.com/javascript/array_map.htm
http://www.tutorialspoint.com/javascript/array_filter.htm
http://api.jquery.com/jQuery.each/
I suggest array functions that are mostly supported (and easily added if not):
[].splice(index, howManyToDelete); // you can alternatively add extra parameters to slot into the place of deletion
[].indexOf(elementToSearchFor);
[].filter(function(){});
Other useful functions include forEach and map.
I agree that combining all the work into one giant loop is ugly (and not always possible), and you gain little by doing it, so readability is definitely the winner. Although you shouldn't need too many loops with these array functions.
The answer that you want:
Create an integer array that stores the number of uses of every quote. Also, a global variable Tot with the total number of quotes already used (i.e., the sum of that integer array). Find also Mean, as Tot / number of quotes.
Chose a random number between 0 and Tot - 1.
For each quote, add Mean * 2 - the number of uses(*1). When you get that that value has exceeded the random number generated, select that quote.
In case that quote is the one currently displayed, either select the next or the previous quote or just repeat the process.
The real answer:
Use a random quote, at the very maximum repeat if the quote is duplicated. The data usages are going to be lost when the user reloads/leaves the page. And, no matter how cleverly have you chosen them, most users do not care.
(*1) Check for limits, i.e. that the first or last quota will be eligible with this formula.
Alternative methods of removing an array element from an array
With ES5's Array.filter() method:
Array.prototype.without = function(v) {
return this.filter(function(x) {
return v !== x;
});
};
given an array a, a.without(v) will return a copy of a without the element v in it.
less occurrences should result in a higher chance compared to the other quotes to be selected for display
You shouldn't mess with chance - as my mathematician other-half says, "chance doesn't have a memory".
What you're suggesting is akin to the idea that numbers in the lottery that haven't come up yet must be "overdue" and therefore more likely to appear. It simply isn't true.
You can write functions that explicitly define what you're trying to do with the loop.
Your first loop is a filter.
Your second loop is a map + some side effect.
I don't know about the other loops, they're weird :P
A filter is something like:
function filter(array, condition) {
var i = 0, new_array = [];
for (; i < array.length; i += 1) {
if (condition(array[i], i)) {
new_array.push(array[i]);
}
}
return new_array;
}
var numbers = [1,2,3,4,5,6,7,8,9];
var even_numbers = filter(numbers, function (number, index) {
return number % 2 === 0;
});
alert(even_numbers); // [2,4,6,8]
You can't avoid the loop, but you can add more semantics to the code by making a function that explains what you're doing.
If, for some reason, you are not comfortable with splice or filter methods, there is a nice (outdated, but still working) method by John Resig: http://ejohn.org/blog/javascript-array-remove/

Categories