Max consecutive items of numbers in array with +1 difference - javascript

I am trying to return the max number of consecutive numbers or same numbers which difference is no more than + 1.
Example*
const array = [1,2,3,5,5,6,6,6,6,7,8]
solution= 556666
const array2 = [2,2,3,4,4,5,5]
solution= 4455
I am a new coder and seems like there should be a simpler way to solve this but I am stuck at this point.
function getMaximumNumberItems(arr) {
let initial = {'0': 0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0 }
let counts = {}
arr.forEach((element) => {
counts[element] = (counts[element] || 0) + 1
})
const numbers = {...initial,...counts}
const arrValues = Object.values(numbers)
let sum = []
for (let i = 0; i < arrValues.length; i++) {
arrValues[i] === arrValues[arrValues.length - 1] ? null : sum.push(arrValues[i] + arrValues[i + 1])
}
console.log(sum)
let maxIndex = sum.indexOf(Math.max(...sum))
}
What I have done is set a count for each number which is numbers, then I add each element with next element to see the max number of elements that are consecutive and add them to an array which is sum. The index of this maximum number should also be the index of the first element that should be returned from counts.
Mi idea was to return key from object and access how many times this number has appeared and add it some way and then use next element of numbers the same way to get the solution.
Obviously I see that this is the worst way of doing it, so would appreciate any help.
Thanks!

You can do it in O(n) time. Take number, match all numbers after that, which difference with it is 1 or smaller. If you find number, which difference is bigger, than 1, then you need to remember the current result and repeat the previous steps, fixing the number of the element from which the best sequence begins and its length.
function maxSubsequence(array) {
let ind = 0;
let bestInd = 0;
let cnt = 1;
let maxCnt = 0;
for (let i = 1; i < array.length; i++) {
if (Math.abs(array[ind] - array[i]) <= 1) {
cnt++;
} else {
if(cnt > maxCnt) {
bestInd = ind;
maxCnt = cnt;
}
cnt = 1;
ind = i;
}
}
if (cnt > maxCnt) {
bestInd = ind;
maxCnt = cnt;
}
return array.slice(bestInd, bestInd + maxCnt);
}
Output:
maxSubsequence(array)
[5, 5, 6, 6, 6, 6]
maxSubsequence(array2)
[4, 4, 5, 5]

Related

how do i find the mode of an array of integers

it is a scenario where a use inputs an array of integers and it returns the most frequent integer.
it is tested 3 times but will fail once, whether its the 1st 2nd or 3rd test.
function arrayMode(array) {
if (array.length === 0) {
return null;
}
var sequence = {};
var maxNo = array[3],
maxCount = 3;
for (var i = 0; i < array.length; i++) {
var Entry = array[i];
if (sequence[Entry] === null)
sequence[Entry] = -1;
else
sequence[Entry]++;
if (sequence[Entry] > maxCount) {
maxNo = Entry;
maxCount = sequence[Entry];
} else if (sequence[Entry] == maxCount) {
maxNo += '&' + Entry;
maxCount = sequence[Entry - 1];
}
return maxNo;
}
}
console.log(arrayMode([1, 3, 3, 3, 1])) // output = 3
console.log(arrayMode([1, 2, 3, 1, 1])) // output = 1
console.log(arrayMode([2, 2, 2, 1])) // output = 2
I think there are several mistakes, if you find an entry not seen previously you set the sequence for that entry to -1, why not 1?
And you initialize maxNo to array[3] and maxCount to 3, why?
Does this make more sense to you?
function arrayMode(arr)
{
var mode = null;
var frequencies = [];
var maxFrequency = 0;
for (var i in arr)
{
var value = arr[i];
// if we haven't seen this value before, init its frequency to 0
if (frequencies[value]===undefined) frequencies[value] = 0;
// increase this value's frequency
frequencies[value]++;
// if this value's frequency is bigger than the max we've seen
// so far, this value is now the new mode.
if (frequencies[value] > maxFrequency)
{
maxFrequency = frequencies[value];
mode = value;
}
}
return mode;
}
If you want to return all modi in case there are more than one entries with the max number of frequencies (for example if for [1,1,2,3,3] you want the mode to be 1 & 3) then you can do so by a simple extra loop at the end.

Finding third smallest number in a given set of numbers with least time complexity

Here's a working algorithm that finds the third smallest number in a given set of numbers.
I was looking for another solutions to the given requirement with less time complexity.
Here's the working code:
Numbers = [3,2,55,-10,-55,5,3,2,1,-5,33,9,-1,4,5];
var x = 0;
var y = 0;
function FindThirdSmallestNumber() {
for(var i=0;i<Numbers.length;i++) {
if (Numbers[i] > Numbers[i+1]) {
x = Numbers[i];
y = Numbers[i+1];
Numbers[i] = y;
Numbers[i+1] = x;
i=-1;
} else {
//
}
}
console.log(Numbers[2]);
}
FindThirdSmallestNumber();
Not sure if this is any faster but it's shorter:
//Use a custom sort function and pass it to the .sort() method
Numbers = Numbers.sort(function(x, y){ return x - y; });
if(Numbers.length > 2){
//At this point, the 3rd item in the array should be the 3rd lowest
console.log(Numbers[2]);
}else {
console.log("There are not 3 numbers in the array.");
}
One option would be to have a separate sorted array of the three smallest numbers so far. Whenever you run across a number smaller than the 3rd smallest (the last in the sorted array), reassign that 3rd index to the new number, and sort it again:
const numbers = [3, 2, 55, -10, -55, 5, 3, 2, 1, -5, 33, 9, -1, 4, 5];
const sortNumeric = (a, b) => a - b;
function FindThirdSmallestNumber(input) {
const [smallestSoFar, numbers] = [input.slice(0, 3), input.slice(3)];
smallestSoFar.sort(sortNumeric);
numbers.forEach((num) => {
if (num < smallestSoFar[2]) {
smallestSoFar[2] = num;
smallestSoFar.sort(sortNumeric);
}
});
return smallestSoFar[2];
}
console.log(FindThirdSmallestNumber(numbers));
Note that implementations that sort the whole array (as other answers do) is O(N log N), while sorting here is only ever done on an array of size 3, which is significantly less complex (O(N log 3) I think, which is equivalent to O(N))
This one should be a lot simpler. Also not sure about this being any faster but in the most simple/obvious cases less code = better performance.
I just sort the array ascending and get the value based on index. So with this code you can get any place; lowest, second lowest, third lowest, etc as long as your index does not go out of range.
const input = [3,2,55,-10,-55,5,3,2,1,-5,33,9,-1,4,5];
function getLowestByRank(data, rank) {
data.sort(function(a, b){ return a - b });
return data[rank - 1];
}
console.log(getLowestByRank(input, 3))
console.log(getLowestByRank(input, 2))
console.log(getLowestByRank(input, 4))
You can use Math.min function to determine the minimum until you find your X smallest number:
Numbers = [3,2,55,-10,-55,5,3,2,1,-5,33,9,-1,4,5];
function FindSmallestNumber(arr, limit) {
var min = '';
for(var counter = 1; counter <= limit; counter ++) {
min = Math.min.apply(Math, arr);
arr.splice(arr.indexOf(min), 1);
}
console.log(min);
}
FindSmallestNumber(Numbers, 3); //3rd smallest number
I think sorting the array is likely the fastest method, but perhaps you want avoid the built–in sort. An alternative is as Chris Li suggests: iterate over the values and just keep the 3 lowest, then return the highest of the three.
I assumed you want to avoid built-in methods, so this only uses some basic array methods and does everything else manually.
// Avoid Math.max
function getMax(arr) {
var max = -Infinity;
for (var i=0, iLen=arr.length; i<iLen; i++) {
if (arr[i] > max) max = arr[i];
}
return max;
}
// If data.length < 4, just returns largest value
// Iterates over data once
function get3rdSmallest(data) {
// Helper to insert value in order
// Expects arr to be length 3 or smaller
function insertNum(arr, num) {
if (!arr.length || num < arr[0]) {
nums.unshift(num);
} else if (num > arr[arr.length-1]) {
arr.push(num);
} else {
arr[2] = arr[1];
arr[1] = num;
}
}
var num, nums = [];
if (data.length < 4) {
return getMax(data);
}
for (var i=0, iLen=data.length; i<iLen; i++) {
num = data[i];
// Insert first 3 values sorted
if (nums.length < 3) {
insertNum(nums, num);
// If num is smaller than largest value in nums,
// remove move largest and insert num
} else if (num < nums[2]){
nums.splice(-1);
insertNum(nums, num);
}
}
// Return highest (last) value in nums
return nums[2];
}
var data = [3,2,55,-10,-55,5,3,2,1,-5,33,9,-1,4,5];
console.log(get3rdSmallest([-4,-22])); // -4
console.log(get3rdSmallest([4,0,1,7,6])); // 4
console.log(get3rdSmallest(data)); // -5

leetcode 3sum assistance, how can i optimize this answer?

I have a solution that seems to pass most of the tests but is too slow. If i'm not mistaken, the complexity is O(n^3) due to the three for loops.
My idea was to start at the first three positions of the array at i, j and k, sum them, and see if it adds up to 0.
The functions objective is:
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
var threeSum = function(nums) {
var originalArray = nums
var lengthArray = nums.length
//sort array smallest to largest
nums.sort(function(a,b) {
return a-b
})
function arrayEqual(array1, array2){
var equal = false
array1.forEach((value1) => {
if(array1 === array2){
equal = true
}
})
return equal
}
var sum = 0;
var answerArray = [];
//start from first digit and add from there
for(var i = 0; i<lengthArray; i++){
for(var j = i+1; j<lengthArray; j++){
for(var k = j+1; k<lengthArray; k++){
if((nums[i]+nums[j]+nums[k] === 0)){
if(!arrayEqual(answerArray, [nums[i],nums[j],nums[k]])){
answerArray.push([nums[i],nums[j],nums[k]])
}
}
}
}
}
return Array.from(new Set(answerArray.map(JSON.stringify)), JSON.parse)
};
How can i get around having to use three for loops to make this work (aka how do i optimize this solution?)
Think this problem in this way. Choose any number from the array say k. Now you need to find two other numbers in the array which add to -k. The resulting sum of three numbers will be k + (-k) = 0.
So this problem is reduced to find two numbers in the array which adds to a given number which is O(n) using two pointers method if given array is sorted.
In a nutshell, sort the array, take each number (k) one by one (O(n)), find two other numbers with sum -k (O(n)).
Total time complexity : O(n) * O(n) = O(n2)
You can solve the problem in a runtime of O(n^2). Here is the solution using JavaScript
var threeSum = function(nums) {
var solutions = [];
var target = 0;
nums.sort(function(a, b) {
return a - b;
});
for(var i = 0; i < nums.length - 2; i++) {
if(i === 0 || (i > 0 && nums[i] !== nums[i - 1])) {
var lo = i + 1;
var hi = nums.length - 1;
var sum = - nums[i];
while(lo < hi) {
if(nums[lo] + nums[hi] === sum) {
solutions.push([nums[i],nums[lo],nums[hi]]);
while (lo < hi && nums[lo] === nums[lo + 1]) lo++;
while (lo < hi && nums[hi] == nums[hi-1]) hi--;
lo++; hi--;
}else if (nums[lo] + nums[hi] > sum) {
hi--;
}else {
lo++;
}
}
}
};
return solutions;
}

Find element that appears odd number of times

I'm trying to solve this exercise of finding the number that appears an odd number of times in an array. I have this so far but the output ends up being an integer that appears an even number of times. For example, the number 2 appears 3 times and the number 4 appears 6 times, but the output is 4 because it counts it as appearing 5 times. How can it be that it returns the first set that it finds as odd? Any help is appreciated!
function oddInt(array) {
var count = 0;
var element = 0;
for(var i = 0; i < array.length; i++) {
var tempInt = array[i];
var tempCount = 0;
for(var j = 0; j <array.length; j++) {
if(array[j]===tempInt) {
tempCount++;
if(tempCount % 2 !== 0 && tempCount > count) {
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
function findOdd(numbers) {
var count = 0;
for(var i = 0; i<numbers.length; i++){
for(var j = 0; j<numbers.length; j++){
if(numbers[i] == numbers[j]){
count++;
}
}
if(count % 2 != 0 ){
return numbers[i];
}
}
};
console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])); //5
console.log(findOdd([1,1,1,1,1,1,10,1,1,1,1])); //10
First find the frequencies, then find which ones are odd:
const data = [1,2,2,2,4,4,4,4,4,4,5,5]
const freq = data.reduce(
(o, k) => ({ ...o, [k]: (o[k] || 0) + 1 }),
{})
const oddFreq = Object.keys(freq).filter(k => freq[k] % 2)
// => ["1", "2"]
If we are sure only one number will appear odd number of times, We can XOR the numbers and find number occurring odd number of times in n Comparisons.XOR of two bits is 1 if they are different else it will be 0. Truth table is below.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
So when we do XOR of all the numbers, final number will be the number appearing odd number of times.
Let's take a number and XOR it with the same number(Appearing two times). Result will be 0 as all the bits will be same. Now let's do XOR of result with same number. Now result will be that number because all the bits of previous result are 0 and only the set bits of same number will be set in the result. Now expanding it to an array of n numbers, numbers appearing even number of times will give result 0. The odd appearance of the number result in that number in the final result.
func oddInt(numbers: [Int]) -> Int {
var result = 0
for aNumber in numbers {
result = result ^ aNumber
}
return result
}
Here is a solution with O(N) or O(N*log(N))
function findOdd(A) {
var count = {};
for (var i = 0; i < A.length; i++) {
var num = A[i];
if (count[num]) {
count[num] = count[num] + 1;
} else {
count[num] = 1;
}
}
var r = 0;
for (var prop in count) {
if (count[prop] % 2 != 0) {
r = prop;
}
}
return parseInt(r); // since object properies are strings
}
#using python
a=array('i',[1,1,2,3,3])
ans=0
for i in a:
ans^=i
print('The element that occurs odd number of times:',ans)
List item
output:
The element that occurs odd number of times: 2
Xor(^)operator when odd number of 1's are there,we can get a 1 in the output
Refer Xor Truth table:
https://www.electronicshub.org/wp-content/uploads/2015/07/TRUTH-TABLE-1.jpg
function oddInt(array) {
// first: let's count occurences of all the elements in the array
var hash = {}; // object to serve as counter for all the items in the array (the items will be the keys, the counts will be the values)
array.forEach(function(e) { // for each item e in the array
if(hash[e]) hash[e]++; // if we already encountered this item, then increments the counter
else hash[e] = 1; // otherwise start a new counter (initialized with 1)
});
// second: we select only the numbers that occured an odd number of times
var result = []; // the result array
for(var e in hash) { // for each key e in the hash (the key are the items of the array)
if(hash[e] % 2) // if the count of that item is an odd number
result.push(+e); // then push the item into the result array (since they are keys are strings we have to cast them into numbers using unary +)
}
return result;
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));
Return only the first:
function oddInt(array) {
var hash = {};
array.forEach(function(e) {
if(hash[e]) hash[e]++;
else hash[e] = 1;
});
for(var e in hash) { // for each item e in the hash
if(hash[e] % 2) // if this number occured an odd number of times
return +e; // return it and stop looking for others
}
// default return value here
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));
That happens because you are setting the element variable each time it finds an odd number, so you are setting it when it find one, three and five 4.
Let's check the code step by step:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j <array.length; j++) {
// If the current number is the same as the one that we are looking for, sum it up
console.log("Current number at position", j, "is", array[j]);
if(array[j]===tempInt) {
tempCount++;
console.log("Number found. Current count is", tempCount);
// Then, if currently there are an odd number of elements, save the number
// Note that you are calling this altough you don't have looped throgh all the array, so the console will log 3 and 5 for the number '4'
if(tempCount % 2 !== 0 && tempCount > count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
What we want to do is to check for the count AFTER looping all the array, this way:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j <array.length; j++) {
// If the current number is the same as the one that we are looking for, sum it up
console.log("Current number at position", j, "is", array[j]);
if(array[j]===tempInt) {
tempCount++;
console.log("Number found. Current count is", tempCount);
}
}
// After getting all the numbers, then we check the count
if(tempCount % 2 !== 0 && tempCount > count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = tempInt;
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
By the way, this is only for you to understand where was the problem and learn from it, although this is not the most optimized way of doing this, as you may notice that you are looking for, let's say, number 2 three times, when you already got the output that you want the first time. If performance is part of the homework, then you should think another way :P
This is because your condition if(tempCount % 2 !== 0 && tempCount > count) is true when the 5th 4 is checked. This updates the count and element variables.
When the 6th 4 is checked, the condition is false.
To fix, move the condition outside the innermost loop so that it's checked only after all the numbers in the array are counted.
function oddInt(array, minCount, returnOne) {
minCount = minCount || 1;
var itemCount = array.reduce(function(a, b) {
a[b] = (a[b] || 0) + 1;
return a;
}, {});
/*
itemCount: {
"1": 1,
"2": 3,
"4": 6,
"5": 2,
"7": 3
}
*/
var values = Object.keys(itemCount).filter(function(k) {
return itemCount[k] % 2 !== 0 && itemCount[k]>=minCount;
});
return returnOne?values[0]:values;
}
var input = [1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5, 7, 7, 7];
console.log(oddInt(input, 3, true));
console.log(oddInt(input, 1, true));
console.log(oddInt(input, 2, false));
"A" is the array to be checked.
function findOdd(A) {
var num;
var count =0;
for(i=0;i<A.length;i++){
num = A[i]
for(a=0;a,a<A.length;a++){
if(A[a]==num){
count++;
}
} if(count%2!=0){
return num;
}
}
}
function oddOne (sorted) {
let temp = sorted[0];
let count = 0;
for (var i = 0; i < sorted.length; i++) {
if (temp === sorted[i]) {
count++;
if (i === sorted.length - 1) {
return sorted[i];
}
} else {
if (count % 2 !== 0) {
return temp;
}
count = 1;
temp = sorted[i];
}
}
}
function oddInt(array) {
let result = 0;
for (let element of array) {
result ^= element
}
return result
}
var oddNumberTimes = (arr) => {
let hashMap = {};
for (let i = 0; i < arr.length; i++) {
hashMap[arr[i]] = hashMap[arr[i]] + 1 || 1;
}
for (let el in hashMap) {
if (hashMap[el] % 2 !== 0) {
return el;
}
}
return -1;
};
You can use bitwise XOR:
function oddInt(array) {
return array.reduce(function(c, v) {
return c ^ v;
}, 0);
}
console.log(oddInt([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]) == 5);
console.log(oddInt([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]) == 10);
Had to implement a solution for a similar problem and here it is:
function findtheOddInt(A) {
let uniqueValues = [...new Set(A)]; // Get the unique values from array A
const odds = [];
uniqueValues.forEach(element => {
const count = A.reduce((acc, cur) => cur === element ? acc + 1: acc, 0) // count the occurrences of the element in the array A
if (count % 2 === 1) {
odds.push(element);
}
});
return odds[0]; // Only the first odd occurring element
}
var arr=[1,2,2,2,2,3,4,3,3,3,4,5,5,9,9,10];
var arr1=[];
for(let i=0;i
{
var count=0;
for(let j=0;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
if(count%2 != 0 )
{
arr1.push(arr[i]);
}
}
console.log(arr1);

How might I find the largest number contained in a JavaScript array?

I have a simple JavaScript Array object containing a few numbers.
[267, 306, 108]
Is there a function that would find the largest number in this array?
Resig to the rescue:
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Warning: since the maximum number of arguments is as low as 65535 on some VMs, use a for loop if you're not certain the array is that small.
You can use the apply function, to call Math.max:
var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306
How does it work?
The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)
So if we call:
Math.min.apply(Math, [1, 2, 3, 4]);
The apply function will execute:
Math.min(1, 2, 3, 4);
Note that the first parameter, the context, is not important for these functions since they are static. They will work regardless of what is passed as the context.
The easiest syntax, with the new spread operator:
var arr = [1, 2, 3];
var max = Math.max(...arr);
Source : Mozilla MDN
I'm not a JavaScript expert, but I wanted to see how these methods stack up, so this was good practice for me. I don't know if this is technically the right way to performance test these, but I just ran them one right after another, as you can see in my code.
Sorting and getting the 0th value is by far the worst method (and it modifies the order of your array, which may not be desirable). For the others, the difference is negligible unless you're talking millions of indices.
Average results of five runs with a 100,000-index array of random numbers:
reduce took 4.0392 ms to run
Math.max.apply took 3.3742 ms to run
sorting and getting the 0th value took 67.4724 ms to run
Math.max within reduce() took 6.5804 ms to run
custom findmax function took 1.6102 ms to run
var performance = window.performance
function findmax(array)
{
var max = 0,
a = array.length,
counter
for (counter=0; counter<a; counter++)
{
if (array[counter] > max)
{
max = array[counter]
}
}
return max
}
function findBiggestNumber(num) {
var counts = []
var i
for (i = 0; i < num; i++) {
counts.push(Math.random())
}
var a, b
a = performance.now()
var biggest = counts.reduce(function(highest, count) {
return highest > count ? highest : count
}, 0)
b = performance.now()
console.log('reduce took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest2 = Math.max.apply(Math, counts)
b = performance.now()
console.log('Math.max.apply took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest3 = counts.sort(function(a,b) {return b-a;})[0]
b = performance.now()
console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest4 = counts.reduce(function(highest, count) {
return Math.max(highest, count)
}, 0)
b = performance.now()
console.log('Math.max within reduce() took ' + (b - a) + ' ms to run')
a = performance.now()
var biggest5 = findmax(counts)
b = performance.now()
console.log('custom findmax function took ' + (b - a) + ' ms to run')
console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5)
}
findBiggestNumber(1E5)
I've found that for bigger arrays (~100k elements), it actually pays to simply iterate the array with a humble for loop, performing ~30% better than Math.max.apply():
function mymax(a)
{
var m = -Infinity, i = 0, n = a.length;
for (; i != n; ++i) {
if (a[i] > m) {
m = a[i];
}
}
return m;
}
Benchmark results
You could sort the array in descending order and get the first item:
[267, 306, 108].sort(function(a,b){return b-a;})[0]
Use:
var arr = [1, 2, 3, 4];
var largest = arr.reduce(function(x,y) {
return (x > y) ? x : y;
});
console.log(largest);
Use Array.reduce:
[0,1,2,3,4].reduce(function(previousValue, currentValue){
return Math.max(previousValue,currentValue);
});
To find the largest number in an array you just need to use Math.max(...arrayName);. It works like this:
let myArr = [1, 2, 3, 4, 5, 6];
console.log(Math.max(...myArr));
To learn more about Math.max:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18];
const maxNumber = Math.max(...inputArray);
console.log(maxNumber);
Finding max and min value the easy and manual way. This code is much faster than Math.max.apply; I have tried up to 1000k numbers in array.
function findmax(array)
{
var max = 0;
var a = array.length;
for (counter=0;counter<a;counter++)
{
if (array[counter] > max)
{
max = array[counter];
}
}
return max;
}
function findmin(array)
{
var min = array[0];
var a = array.length;
for (counter=0;counter<a;counter++)
{
if (array[counter] < min)
{
min = array[counter];
}
}
return min;
}
Simple one liner
[].sort().pop()
Almost all of the answers use Math.max.apply() which is nice and dandy, but it has limitations.
Function arguments are placed onto the stack which has a downside - a limit. So if your array is bigger than the limit it will fail with RangeError: Maximum call stack size exceeded.
To find a call stack size I used this code:
var ar = [];
for (var i = 1; i < 100*99999; i++) {
ar.push(1);
try {
var max = Math.max.apply(Math, ar);
} catch(e) {
console.log('Limit reached: '+i+' error is: '+e);
break;
}
}
It proved to be biggest on Firefox on my machine - 591519. This means that if you array contains more than 591519 items, Math.max.apply() will result in RangeError.
The best solution for this problem is iterative way (credit: https://developer.mozilla.org/):
max = -Infinity, min = +Infinity;
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
if (numbers[i] < min)
min = numbers[i];
}
I have written about this question on my blog here.
Yes, of course there exists Math.max.apply(null,[23,45,67,-45]) and the result is to return 67.
Don't forget that the wrap can be done with Function.prototype.bind, giving you an "all-native" function.
var aMax = Math.max.apply.bind(Math.max, Math);
aMax([1, 2, 3, 4, 5]); // 5
You could also extend Array to have this function and make it part of every array.
Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];
console.log( myArray.max() );
You can also use forEach:
var maximum = Number.MIN_SAFE_INTEGER;
var array = [-3, -2, 217, 9, -8, 46];
array.forEach(function(value){
if(value > maximum) {
maximum = value;
}
});
console.log(maximum); // 217
Using - Array.prototype.reduce() is cool!
[267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val)
where acc = accumulator and val = current value;
var a = [267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val);
console.log(a);
A recursive approach on how to do it using ternary operators
const findMax = (arr, max, i) => arr.length === i ? max :
findMax(arr, arr[i] > max ? arr[i] : max, ++i)
const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const max = findMax(arr, arr[0], 0)
console.log(max);
You can try this,
var arr = [267, 306, 108];
var largestNum = 0;
for(i=0; i<arr.length; i++) {
if(arr[i] > largest){
var largest = arr[i];
}
}
console.log(largest);
I just started with JavaScript, but I think this method would be good:
var array = [34, 23, 57, 983, 198];
var score = 0;
for(var i = 0; i = array.length; i++) {
if(array[ i ] > score) {
score = array[i];
}
}
var nums = [1,4,5,3,1,4,7,8,6,2,1,4];
nums.sort();
nums.reverse();
alert(nums[0]);
Simplest Way:
var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]);
Run this:
Array.prototype.max = function(){
return Math.max.apply( Math, this );
};
And now try [3,10,2].max() returns 10
Find Max and Min value using Bubble Sort
var arr = [267, 306, 108];
for(i=0, k=0; i<arr.length; i++) {
for(j=0; j<i; j++) {
if(arr[i]>arr[j]) {
k = arr[i];
arr[i] = arr[j];
arr[j] = k;
}
}
}
console.log('largest Number: '+ arr[0]);
console.log('Smallest Number: '+ arr[arr.length-1]);
Try this
function largestNum(arr) {
var currentLongest = arr[0]
for (var i=0; i< arr.length; i++){
if (arr[i] > currentLongest){
currentLongest = arr[i]
}
}
return currentLongest
}
As per #Quasimondo's comment, which seems to have been largely missed, the below seems to have the best performance as shown here: https://jsperf.com/finding-maximum-element-in-an-array. Note that while for the array in the question, performance may not have a significant effect, for large arrays performance becomes more important, and again as noted using Math.max() doesn't even work if the array length is more than 65535. See also this answer.
function largestNum(arr) {
var d = data;
var m = d[d.length - 1];
for (var i = d.length - 1; --i > -1;) {
if (d[i] > m) m = d[i];
}
return m;
}
One for/of loop solution:
const numbers = [2, 4, 6, 8, 80, 56, 10];
const findMax = (...numbers) => {
let currentMax = numbers[0]; // 2
for (const number of numbers) {
if (number > currentMax) {
console.log(number, currentMax);
currentMax = number;
}
}
console.log('Largest ', currentMax);
return currentMax;
};
findMax(...numbers);
Find the largest number in a multidimensional array
var max = [];
for(var i=0; arr.length>i; i++ ) {
var arra = arr[i];
var largest = Math.max.apply(Math, arra);
max.push(largest);
}
return max;
My solution to return largest numbers in arrays.
const largestOfFour = arr => {
let arr2 = [];
arr.map(e => {
let numStart = -Infinity;
e.forEach(num => {
if (num > numStart) {
numStart = num;
}
})
arr2.push(numStart);
})
return arr2;
}
Should be quite simple:
var countArray = [1,2,3,4,5,1,3,51,35,1,357,2,34,1,3,5,6];
var highestCount = 0;
for(var i=0; i<=countArray.length; i++){
if(countArray[i]>=highestCount){
highestCount = countArray[i]
}
}
console.log("Highest Count is " + highestCount);

Categories