Finding the lowest number in an array using split('') and reverse(); - javascript

I am trying to find the min value of an array, and am trying to do it by sorting the array, and then reversing the array, and then calling the very first index of the array.
Unfortunately with what I have been trying, I keep getting 9. (don't know why) Can anybody take a quick look at what I have been doing and bail me out here? (i'm using js)
var minny = [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest = function (minny){
minny = minny.sort('');
var sorted = minny + " ";
sorted = minny.reverse('').join('');
return sorted[0];
}
console.log(smallest(minny))

By default the sort method sorts elements alphabetically(11 comes before 9) and therefore you need to add a compare function as a param.
var smallest = function (minny) {
minny = minny.sort(function(a, b) { return a - b; });
return minny[0];
}
console.log(smallest(minny))
JSFIDDLE.

Based on your code, you could just do
return minny.sort()[0];
So, your full code example becomes
var minny = [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest = function (minny){
return minny.sort()[0];
}
console.log(smallest(minny))

You're calling minny.sort('') which is using the default natural sort, so 11 and 25 end up near the beginning because of the 1 and 2.
What you have to do is call sort with a function that compares numbers, such as:
minny.sort(function(a,b) { return b-a; });
This will sort minny the way you want it.
There is no need to even call reverse and join afterwards, just return the first item. "return sorted[0]" is fine but will fail if there are no items, so you might just want to call "return sorted.shift()" instead. This will return the first item too, but won't fail if the array is empty.
PS. your call to minny.reverse also has an empty string as a parameter. That's not needed, reverse takes no parameters.

sort() sorts alphabetically by string representation, so in your case it would result in 1, 11, 2, 2, 25, .... You have to provide a comparison function for correct integer sorting, although in your specific case it doesn't really make a difference.
var smallest = function (minny){
minny = minny.sort(function(a, b){return a-b});
return minny[0];
}
See jsfiddle

Using sort is fairly short code to write, and it will return the correct number if you use minny.sort(function(a,b){return a-b})[0].
If you have a large unordered array you are running the comparison many times and you are sorting the array, which is not usually what you want to do to an array.
It may be better to just iterate the members and compare each just once to the lowest fond so far.
var minny= [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest= function(minny){
var min= Infinity;
minny.forEach(function(next){
if(next<min) min= next;
});
return min;
}
Or use Math.min, if this is code golf:
Math.min.apply(Array,minny);

Related

find unpaired element in array - how does this work?

There was a question on how to find the unpaired element in an array. So if an element occurs in an array 3 times, or 5 times, or any unpaired times.
The fastest method (it works ok!) was this:
function pairing (A) {
var s = new Set;
A.forEach(function(v) {
s.delete(v) || s.add(v)
});
return s.values().next().value;
}
const arr = [1, 2, 5, 1, 2, 5, 7, 8, 7, 7, 8, 7, 1, 1, 3];
console.log(pairing(arr));
It will give 3 as a result, that's the unpaired element.
The solution works, but I don't know what it does. Please somebody give me an explanation for this!
What is this line:
s.delete(v) || s.add(v)
I can't interpret it.
And, this one:
s.values().next().value;
?
Please detail what is happening here.
Thank you !
The logical or operator (||) short-circuits and returns the first value that is not false (or falsey, but that is not relevant here).
Set#delete returns true if the element was deleted, i.e. it did originally exist in the set, and false otherwise. Set#add returns true if the element was added, i.e. it did not already exist in the set, and false otherwise.
Thus, s.delete(v) || s.add(v) is really saying delete v if it already exists in the set; otherwise, add it. This works due to the short-circuiting of the logical or operator: if set.delete(v) returns true, s.add(v) will never be executed.
Set#values returns the iterator for the values of the set in the order they were inserted. .next() gets the next element from the iterator and .value gets the value of that element. In this case, it returns the first and only element of the Set, which is the unpaired element.
On another note, the standard and most efficient way to solve this problem for integers is to apply the bitwise XOR (^) operator. Since a ^ a === 0 for all integers, simply XORing all the numbers in the array will find the number that appeared an odd amount of times.
const arr = [1, 2, 5, 1, 2, 5, 7, 8, 7, 7, 8, 7, 1, 1, 3];
function unpaired(arr){
return arr.reduce((acc,curr)=>acc^curr,0);
}
console.log(unpaired(arr));
s.delete(v) || s.add(v) - this delete a value if present in a set or add if not already present in a set "s".
s.values().next().value; - this one return the value left in the set(unpaired one)
As per the code -
function pairing (A) {
var s = new Set;
A.forEach(function(v) {
console.log(s)
s.delete(v) || s.add(v)
});
return s.values().next().value;
}
const arr = [1, 2, 5, 1, 2, 5, 7, 8, 7, 7, 8, 7, 1, 1, 3];
console.log(pairing(arr));
}
const arr = [1, 2, 5, 1, 2, 5, 7, 8, 7, 7, 8, 7, 1, 1, 3];
console.log(pairing(arr));
The output is
Simplified version of the function you posted. Hope it is understandable now
var set = new Set();
const arr = [1, 2, 5, 1, 2, 5, 7, 8, 7, 7, 8, 7, 1, 1, 3];
arr.forEach(ele => {
if(set.has(ele)){
set.delete(ele);
} else {
set.add(ele);
}
})
console.log(set.values().next().value);
// This gives the element left over in set which is unpaired.

How will I sort a list using javascript?

I want to sort a list on my site using JavaScript. I've search on w3c but it seems that I need to make a button for that. I want to sort a list automatically. Please help me.
Use .sort(<compare function>)
From MDN:
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Examples
For Ascending
var arr = [1, 6, 3, 8, 10, 3, 4, -1]; //unsorted array
arr.sort(function (a, b) {
return a - b;
});
result: -1,1,3,3,4,6,8,10
or
var arr = [1, 6, 3, 8, 10, 3, 4, -1]; //unsorted array
arr.sort(sortAscending);
function sortAscending(a, b) {
return a - b;
}
result: -1,1,3,3,4,6,8,10
For Descending
var arr = [1, 6, 3, 8, 10, 3, 4, -1]; //unsorted array
arr.sort(sortDescending);
function sortDescending(a, b) {
return b - a;
}
result: 10,8,6,4,3,3,1,-1
NOTE The compare function being passed may not suit your needs so you need to be more specific about what you're sorting for an answer that's more specific to your problem

Iteratively adding up first and last numbers in an array

I'm trying to write a function that continually adds together the first and last elements of an array using forEach with array.shift() + array.pop().
The problem is that the for-loop doesn't complete the innermost numbers, and so the array is always left with 2 values inside of it.
Code:
function choreAssignment(chores) {
chores.sort(function(a, b) {return a - b});
var assignment = [];
chores.forEach(function() {
assignment.push((chores.pop() + chores.shift()));
});
return assignment.sort(function(a, b) {return a - b});
}
The above code works as expected, but it leaves the innermost two values inside the chores array.
For example if I run:
Code:
var arr = [1, 4, 7, 2, 5, 9, 4, 3];
choreAssignment(arr);
I get:
[8, 9, 10]
Ie, it adds 9 & 1, 7 & 2, 5 & 3, but it leaves [4, 4] inside the array.
I'm not sure why this is. Thank you.
Try changing the forEach to:
while (chores.length) {
assignment.push((chores.pop() + chores.shift()));
}
Note this assumes there are always an even number of elements in array

what does max() function do in javascript if array has several equally large numbers

If we get something like
array=[5,5,5,5,3,2];
return Math.max.Apply(Math,array);
How do I get it to return the numbers from first to last if such a case occurs.
To answer the question in the title:
what does max() function do in javascript if array has several equally
large numbers
The answer is, nothing. Math.max() doesn't act on arrays.
You can pass an array by spreading the items as arguments to max():
Math.max(...[1,2,3]) // 3
Or as you've seen, with apply():
Math.max.apply(Math, [1,2,3]) // 3
If the question is more:
What does Math.max() do when more than one of the same maximum number is given?
The answer is, it returns that number:
const a = [5, 5, 5, 5, 3, 2]
const max = Math.max(...a)
console.log(max) // 5
This question is confusing:
How do I get it to return the numbers from first to last if such a case occurs.
You want it to return a sorted array? From [5, 5, 5, 5, 3, 2] to [2, 3, 5, 5, 5, 5]?
a.sort() // [2, 3, 5, 5, 5, 5]
You want dupes removed? From [5, 5, 5, 5, 3, 2] to [2, 3, 5]?
Array.from(new Set(a)) // [2, 3, 5]
Could you clarify your question?
The best way to do this is the following:
var a = [5,5,5,5,3,2];
var largest = Math.max.apply(null,a)
var filtered = a.filter(function(item) {
item === largest
});
Where filtered will have contain all the largest elements.
In #Clarkie's example, he's calling Math.max more frequently than needed.
In both Dan and Clarkie's example they're capitalizing Apply which is incorrect, the correct function to call is Math.max.apply and Math need not be passed in as the first argument.
See the following for a working example:
https://jsfiddle.net/fx5ut2mm/
Modifying #Clarkie's very nice idea. We can boil it down to...
var a = [5,5,5,5,3,2],
m = Math.max(...a),
f = a.filter(e => e == m);
document.write("<pre>" + JSON.stringify(f) + "</pre>");

Javascript Sub-Array

I recently ran into the problem where I would like to select multiple elements from an array, to return a sub-array. For example, given the array:
a = [1, 5, 1, 6, 2, 3, 7, 8, 3]
And the index array of:
i = [3, 5, 6]
I want to select all elements in a, who's index appears in i. So the output in my simple example would be:
[6, 3, 7]
I completely realise I could use a for loop over i and construct a new array then use Array.push(a[index (in i)]) to add in each, but I was wondering if there was a clearer/cleaner way to achieve this (possibly using underscore.js, or something similar).
i.map(function(x) { return a[x]; })
// => [6, 3, 7]
You can try this
a = [1, 5, 1, 6, 2, 3, 7, 8, 3];
i = [3,5,6];
var res= []; //for show result array
for (var n in a){ //loop a[]
for(var index in i){ //loop i[]
if( n == i[index] ) //n is index of a[]
res.push(a[n]); //add array if equal n index and i[] value
}
}
alert(res); // 6,3,7
You could use map function to achieve your desired result.
var a = [1, 5, 1, 6, 2, 3, 7, 8, 3];
var i = [3, 5, 6];
var mapped = i.map(function(index) {
return a[index];
});
console.log(mapped);
Here is the working jsfiddle.
However with above example, map not be available in all browsers yet. Here is the quote from documentation of map.
map was added to the ECMA-262 standard in the 5th edition; as such it
may not be present in all implementations of the standard.
If your code will be running in old browsers then you will need to add a polyfill. However there are libraries that give you similar functionality with polyfills for older browsers. Along with map function, underscodejs has tons of other helpful functions. I higly recommend you to look at what underscorejs has to offer. It provides tons of helper functions and has quite wide range browser support.
You would do following in underscorejs and wont have to worry if your code works in cross browsers.
var a = [1, 5, 1, 6, 2, 3, 7, 8, 3];
var mapped = _.map([3, 5, 6], function(index) {
return a[index];
});
alert(mapped);
Here is jsfiddle for that.

Categories

Resources