Javascript array store each value in variable - javascript

How can I store each value of javascript array in variable such that I can use it to perform further actions?
Eg:
var plan = [100, 200];
var months = [3, 6];
for (var i = 0; i < plan.length; i++) {
p_det = plan[i];
}
for (var i = 0; i < months.length; i++) {
m_det = months[i];
}
console.log(p_det * m_det); //Gives me value of 200*6
Mathematical action I've to perform such that ((100 * 3) + (200 * 6))
Is storing each value in variable will help? How can I achieve this?

Storing each element in a variable won't help, you already can access those values using the array[index]. Assuming your arrays are the same length, you can calculate what you want in a loop:
for (var sum = 0, i = 0; i < plan.length; i++) {
sum += plan[i]*month[i];
}
console.log( sum );

you can achieve it with reduce assuming that both arrays have same length
var plan = [100, 200];
var months = [3, 6];
var sum = plan.reduce(function(sum, val, index) {
return sum + months[index] * val;
}, 0);
snippet.log(sum)
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

A simple while loop will do. It works for any length, because of the Math.min() method for the length.
function s(a, b) {
var i = Math.min(a.length, b.length),
r = 0;
while (i--) {
r += a[i] * b[i];
}
return r;
}
document.write(s([100, 200], [3, 6]));

In ES6:
sum(plan.map((e, i) => e * months[i])
where sum is
function sum(a) { return a.reduce((x, y) => x + y); }

Related

best way to find two number in an array which their sum be a specific number

what is the best algorithm to find two numbers in an array which their sum be a specific number ? for example Array = [1,5,73,68,2] and specific number is 70 . output must be 68 + 2 = 70
so if you want a better solution with better time complexity you can reach O(n) instead of O(n^2) and iterating the array only once.
but you need a data structure that has O(1) for finding data, something like hashmap.
and code would be like this:
function find(array, sum){
let answer = {}
for(const num of array){
if(answer[num]){
return { first: sum - num, second: num}
}
answer[sum - num] = true
}
return false
}
let arr = [ 2, 5, 7, 3, 82]
console.log(find( arr, 10))
I do my try, hope this helps.
function getPairs(arr, n, sum)
{ let temp = []
for (let i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
temp.push([arr[i],arr[j]])
return temp
}
let arr = [1,2,3,4]
console.log(getPairs(arr, arr.length, 3))
You can use a for loop
sums=[]
function findinarray(specialnumb){
array = [1,5,73,68,2]
for(let i=0;i<array.length;i++){
for(let j=1+i;j<array.length;j++){
o=array[i]
b=array[j]
if(o+b==specialnumb)
sums.push(o,b)
}
}
return sums
}
console.log(findinarray(70))
function example(){
var numbersArray = ['1','5','73','68','2'];
var number = 70;
for (let i = 0; i < numbersArray.length; i++) {
for (let j = 0; j < numbersArray.length; j++) {
if(Number(numbersArray[i])+Number(numbersArray[j]) == number){
console.log('found this:'+numbersArray[i]+'+'+numbersArray[j] +'='+number)
}
}
}
}
example();
Ofcourse you dont have to use console.log , this is just an example.
A simple example , i'm pretty sure there are another ways to do it.
I hope this will help you
Here you go: Working solution. Just run snippet to see in action.
You can pass array() to this function and total number you want to count in that array. In return it will console.log the indexes totaling that number which you wanted.
function checkSum(arrayValues, total) {
var map = [];
var indexxxx = [];
for (var x = 0; x < arrayValues.length; x++) {
if (map[arrayValues[x]] != null) {
var index = map[arrayValues[x]];
indexxxx[0] = index;
indexxxx[1] = x;
break;
} else {
map[total - arrayValues[x]] = x;
}
}
console.log('Array Index at ' + indexxxx[0] + ' & ' + indexxxx[1] + ' sums equals to ' + total)
}
checkSum([1, 5, 73, 68, 2], 70)
If you want to know the exact value totalling the number then you do this:
function checkSum(arrayValues, total) {
var indexxxx = [];
for (var x = 0; x < arrayValues.length; x++) {
for (var j = 1 + x; j < arrayValues.length; j++) {
o = arrayValues[x]
b = arrayValues[j]
if (o + b == total)
indexxxx.push(o, b)
}
}
console.log('Array value at ' + indexxxx[0] + ' & ' + indexxxx[1] + ' sums equals to ' + total)
}
checkSum([1, 5, 73, 68, 2], 70)
I just created this utility in order to find the pairs whose sum will be equal to the provided/expected sum. Here I have not used nested loops. This will also eliminate duplicate pairs.
getPairs = (array, sum) => {
const obj = {}
const finalResult = []
array.forEach(d => {
obj[sum - d] = d
})
Object.keys(obj).forEach(key => {
if (obj[sum - key]) {
finalResult.push([parseInt(key), sum - key])
delete obj[key]
}
})
return finalResult
}
const array = [1, 5, 73, 68, 2, 4, 74]
const sum = 78
console.log(getPairs(array, sum))
Hope this helps.

Two Sum Leetcode in Javascript - code looks correct but Leetcode says it's wrong

I'm working on the 'Two Sum' problem in Leetcode.
I'm sure this code is correct, I've tested it in Repl and it looks correct there, but Leetcode is giving me an error.
Here's my code:
var arr = [];
var twoSum = function(nums, target) {
for(var i = 0; i < nums.length; i++){
for(var j = i+1; j < nums.length; j++){
console.log(nums[i] + ', ' + nums[j]);
var tot = nums[i] + nums[j];
if(tot === target){
arr.push(i,j);
console.log(arr);
return arr;
}
}
}
};
//var a = [2, 7, 11, 15];
//var b = 9;
var a = [2, 3, 4];
var b = 6;
twoSum(a, b);
The error I'm getting is as follows:
Input:
[3,2,4]
6
Output:
[0,1,1,2]
Expected:
[1,2]
Why is it expecting [1, 2]? Surely it should expect [0, 1] in this case, and then why is my code adding to the arr array twice? It looks like a bug to me...
Note: I see there's many posts about this problem on Leetcode, but none address the specific issue I have run into in Javascript.
Why is it expecting [1, 2]?
Because 2 + 4 = 6
Surely it should expect [0, 1] in this case
No, because 3 + 2 = 5
and then why is my code adding to the arr array twice?
Because you declared the array outside of the function. It is being re-used for every call to the function. Move the array declaration into your twoSum function or even better: Simply return [i, j] instead of pushing into the empty array.
Here is another solution you can try...
var twoSum = function(nums, target) {
let map = {};
for (let i = 0; i < nums.length; i++) {
let compliment = target - nums[i];
if (map[compliment]) {
return [(map[compliment] - 1), i];
} else {
map[nums[i]] = i + 1;
}
}
};
twoSum([2, 3, 4],6);
Click Here to RUN
Here is an optimum solution
/**
* #param {number[]} nums
* #param {number} target
* #return {number[]}
*/
function twoSum(nums, target) {
const numsObjs = {}; // create nums obj with value as key and index as value eg: [2,7,11,15] => {2: 0, 7: 1, 11: 2, 15: 3}
for (let i = 0; i < nums.length; i++) {
const currentValue = nums[i];
if (target - currentValue in numsObjs) {
return [i, numsObjs[target - currentValue]];
}
numsObjs[nums[i]] = i;
}
return [-1, -1];
}
console.log(twoSum([2, 7, 11, 15], 9))
This is my solution, which is a brute force method that uses javascript to search for all possible pairs of numbers.
var twoSum = function(nums, target) {
let numarray = new Array(2);
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
numarray[0] = i;
numarray[1] = j;
}
}
}
return numarray;
};

Given an array of integers, find the pair of adjacent elements that has the largest product and return that product

Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
and here is my code
function adjacentElementsProduct(inputArray) {
var arr = inputArray;
var x=0;
var y=0;
var p=0;
for(var i=0;i<arr.length;i++){
x=arr[i];
y=arr[i+1];
if(x*y>p){
p=x*y;
};
};
return p;
};
the problem is all the tests works fine but except the array with the negative product as it shown in the attached photo
can anyone help .. and thanks in advance
You could start with a really large negative value, instead of zero.
var p = -Infinity;
You are initializing the variable p to zero. That means any multiplication values smaller than that are not accepted. Rather set it to the smallest possible integer value:
var p = Number.MIN_SAFE_INTEGER;
function adjacentElementsProduct(inputArray) {
var arr = inputArray;
var x = 0;
var y = 0;
var p = Number.MIN_SAFE_INTEGER;
for (var i = 0; i < arr.length; i++) {
x = arr[i];
y = arr[i + 1];
if (x * y > p) {
p = x * y;
};
};
return p;
};
console.log(adjacentElementsProduct([-23, 4, -3, 8, -12]));
This is quite simple actually
function adjacentElementsProduct(inputArray) {
let max = -Infinity;
for (let i = 1; i < inputArray.length; i++) {
max = Math.max(inputArray[i] * inputArray[i - 1], max);
}
return max;
}
This is quite simple actually
const solution = (inputArray) => Math.max(...inputArray.slice(0, -1).map((n, index) => n * inputArray[index + 1]))
console.log(solution([3, 6, -2, -5, 7, 3]))
function solution(inputArray: number[]): number {
var max = -Infinity;
for(var i=0; i+1<inputArray.length; i++)
{
if(max<(inputArray[i]*inputArray[i+1])){
max=inputArray[i]*inputArray[i+1];
}
}
return max;
}
console.log(solution([2,3,6]))
I had the same problem at first, defining the first max as 0. Then i came up with this:
function solution(inputArray) {
let products = inputArray.map(function(x, index){
return inputArray[index+1] != undefined? x *inputArray[index+1] : -Infinity;
})
return Math.max(...products);
}
Problem:
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. #javascript #arraymethods
function solution(inputArray) {
let productsArr = []; // to hold the products of adjacent elements
let n = 0;
for (let i = 0; i < inputArray.length; i++) {
if (i < inputArray.length - 1)
{
productsArr[n] = inputArray[i] * inputArray[i + 1];
n++;
}
}
return productsArr.reduce((aggr, val) => Math.max(aggr, val)); // to find out the biggest product
}
Here's a very simple implementation without using any additional variables (actually less), and no special values. Just simple logic.
function adjacentElementsProduct(inputArray) {
var c =inputArray[0]*inputArray[1];
var p = c;
for(var i=1;i<inputArray.length;i++){
console.log(c);
var c=inputArray[i]*inputArray[i+1];
if(c > p){
p=c;
};
};
return p;
};
console.log("minimum product = " + adjacentElementsProduct([-23,4,-3,8,-12]));
What I did was, initialize a variable c (current product) with the product of first two elements of the array. And then I declared the variable p and initialize it to c. This way, all other products are compared to this product. Rest is simple.
Hope it helps. :)
you can try to initialize a integer as negative infinity value -math.inf and then use the python ternary operator var=true if condition else false to find the maximum value
code in python
def adjacentarray(a):
maximum=-math.inf
for i,in range(0,len(a)-1):
maximum=a[i]*a[i+1] if a[i]*a[i+1]>maximum else maximum
return maximum
code in javascript
function adjacentElementsProduct(a) {
var maximum=-Infinity;
for (var i=0;i<a.length-1;i++){
maximum= a[i]*a[i+1]>maximum?a[i]*a[i+1]:maximum;
}
return maximum;
}
function solution(inputArray) {
let first, second, sum = []
inputArray.map((arr,index)=>{
first = arr;
second = inputArray[index+1]
if(second == undefined){
return second
}
return sum.push(first * second)
})
let last = sum.sort().reduce((pre,next)=> {
return pre > next ? pre : next
})
return last;
}
//Kotlin
fun solution(inputArray: MutableList<Int>): Int {
var result: Int = Int.MIN_VALUE
for (i in 0..inputArray.size - 2) {
if (inputArray[i] * inputArray[i + 1] > result)
result = inputArray[i] * inputArray[i + 1]
}
return result
}
import 'dart:math';
int solution(List<int> inputArray) {
//assumption for highest number
int highestNumber = inputArray[0] * inputArray[1] ;
//we'll go through the array to campare the highestNumber
//with next index
for(var i = 1 ; i < inputArray.length ; i++){
highestNumber = max(highestNumber, inputArray[i] * inputArray[i - 1]);
}
return highestNumber;
}
In Javascript, you could use the reduce method from an array to avoid iterating in a for loop, just like this.
function solution(inputArray) {
let maxProd = []
inputArray.reduce((accumulator, currentValue) => {
maxProd.push(accumulator*currentValue)
return currentValue
},
);
return Math.max(...maxProd)
}
Once you have in the maxProd array the products, you use the spread operator to get the numbers and using Math.max() you get the largest
python solution
You can make a loop from 1 to end of your list and do the following arithmetic operations
def solution(inputArray):
list1 =[]
for i in range(1,len(inputArray)):
list1.append(inputArray[i]*inputArray[i-1])
return max(list1)
Here is a solution in PHP that is quite simple.
function solution($inputArray) {
$largest = null;
$pos = null;
for($i = 0; $i < count($inputArray) -1; $i++){
$pos = ($inputArray[$i] * $inputArray[$i+1]);
if($largest < $pos){
$largest = $pos;
}
}
return $largest ?? 0;
}
You can try to create a new array of length (arr.length-1) inside the function and append the products of adjacent numbers to this new array. Then find the largest number in the array and return it. This will solve the problem with negative product.
function adjacentElementsProduct(inputArray) {
var arr = inputArray;
var prodArr[];
var p;
for (var i = 0; i < arr.length-1; i++) {
prodArr[i] = arr[i]*arr[i+1];
};
for (j=prodArr.length; j--){
if (prodArr[j] > p) {
p = prodArr[j];
};
return p;
};
console.log(adjacentElementsProduct([-23, 4, -3, 8, -12]));
The var p which saves the max product should be initialized as small as possible instead of a 0. So that when the product is negative, it will still meet the if condition and save the value.
Here is a C# solution:
static void Main(string[] args)
{
int[] arr = { 1, -4, 3, -6, -7, 0 };
Console.WriteLine(FindMaxProduct(arr));
Console.ReadKey();
}
static int FindMaxProduct(int[] arr) {
int currentProduct = 0;
int maxProduct = int.MinValue;
int a=0, b = 0;
for (int i = 0, j = i + 1; i < arr.Length - 1 && j < arr.Length; i++, j++)
{
currentProduct = arr[i] * arr[j];
if (currentProduct>maxProduct) {
a = arr[i];
b = arr[j];
maxProduct = currentProduct;
}
}
Console.WriteLine("The max product is {0}, the two nums are {1} and {2}.",maxProduct,a,b);
return maxProduct;
}
function solution(inputArray) {
let f, s, arr = []
for(let i=0; i<inputArray.length; i++){
f = inputArray[i]
s = inputArray[i+1]
arr.push(f*s)
}
let max = arr.sort((a, b) => b - a)
return max[0]
}
console.log(solution([3, 6, -2, -5, 7, 3]))
This should help, wrote it in python. Concept: Pass an empty list, for every consecutive product keep storing it in the list. Then just return the max value.
def consecutive_product_max(a):
lst2 = []
for i in range(0, len(a)-1):
x = a[i] * a[i+1]
lst2.append(x)
return max(lst2)

Javascript sum of arrays and average

I have an issue with getting the sum of two arrays and combining their averages while rounding off.
I don't want to hardcode but rather pass two random arrays. so here is the code but it keeps returning NaN
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
arr = [];
a = [];
b = [];
arr[0] = a;
arr[1] = b;
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
If you wanted to do it a bit more functionally, you could do something like this:
function sumAverage(arrays) {
const average = arrays.reduce((acc, arr) => {
const total = arr.reduce((total, num) => total += num, 0);
return acc += total / arr.length;
}, 0);
return Math.round(average);
}
console.log('sum average:', sumAverage([[1,2,3], [4,5,6]]));
Just try this method..this kind of issues sometimes occured for me.
For example
var total = 0;
total = total + sum / a.length;
And every concat use this method..
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle
function sumAverage(arr) {
var result = 0;
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for(var j = 0; j < a.length; j++ ){
sum += a[j] ;
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for(var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));
As said in comments, you reset your arguments...
Use the variable "arguments" for dynamic function parameters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I suggest to use two nested loops, one for the outer array and one for the inner arrays. Then sum values, calculate the average and add averages.
function sumAverage(array) {
var result = 0,
sum,
i, j;
for (i = 0; i < array.length; i++) {
sum = 0;
for (j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
result += Math.round(sum / array[i].length);
}
return result;
}
console.log(sumAverage([[2, 3, 4, 5], [6, 7, 8, 9]])); // 12
The problem is that you are emptying arr by saying arr = [].
Later, you are iterating over a which is empty too.
Again when you say total += sum / a.length;, sum is 0 and a.length is 0 so 0/0 becomes NaN. Similarly for math. Adding Nan to NaN is again NaN and that's what you get.
Solution is to not empty passed arr and modify your code like below:
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total = sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math = add / b.length;
result = math + total;
result = Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
Basically I see a mistake here:
arr[0] = a; arr[1] = b;
That should be
a= arr[0]; b= arr[1];
and then remove:
arr = [];
I suggest you write your function like this:
function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}

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