I've a multidimensional array
arr = [[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]],
[[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]]
];
and so on ... but the dimension of the arr is not fixed, is variable.
I've a variable that tell me where to point my attention
var number = 2;
So my goal is the look in any arr[i] and find the max 1st argument based on the 2nd argument, I try to explain better my self, in this particular case if number is 2 my expectation is to have from arr:
for the 1st array in arr -> 6 (because the second argument is 1,1,1,2,2,2,3 so I've to point at the last 2 and return the 1st argument)
for the 2nd array in arr -> 3 (because 2 is missing and the 1 is the last second argument)
I know is a little tricky
My first idea was to make a for loops where I delete all value over my number, then I can take the very last one, but I think I'm over-complicating all.
There is a better and fast way to achieve the same result?
J
You present lists (arrays) of pairs of numbers, where the pairs are sorted in ascending order, first by the second number, then by the first.
What you seem to ask for is: Given a number to search for among the second numbers, e.g. number = 2, find the last pair where the second number is less than or equal to this number, and return the corresponding first number in this pair.
You state that you could use for loops to solve the problem. A straightforward approach could be like the following snippet:
var arr = [[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]],
[[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]]
];
var findNumber = 2;
var result = [];
for(var i = 0; i < arr.length; i++){
var maxIndex = -1;
for(var j = 0;
j < arr[i].length && arr[i][j][1] <= findNumber;
j++){
maxIndex = j;
}
result.push(arr[i][maxIndex][0]);
}
//gives the expected answers 6 and 3
console.log(result);
Then you ask:
There is a better and fast way to achieve the same result?
A solution involving .map and .reduce could be considered more elegant, like the following:
var arr = [[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]],
[[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]]
];
var findNumber = 2;
var result = arr.map(function(val){
return val[val.reduce(function(acc, curr, index){
return curr[1] <= findNumber? index : acc;
}, -1)][0];
});
//gives the expected answers 6 and 3
console.log(result);
However, in terms of performance, for loops are likely to perform better (run faster) and are easy to comprehend.
In addition, you mention that
the dimension of the arr is not fixed
You would need to post some code examples on how the dimensionality of your data may vary before it would be possible to provide any answer that handles this aspect.
Update
To handle a single array of pairs, you do not need the outer loop or .map(). Putting the solution above into a reusable function:
function lookupFirstNumberFromSecond(secondNumberToFind, arr){
var j = 0, maxIndex = -1;
while(j < arr.length && arr[j][1] <= secondNumberToFind){
maxIndex = j++;
}
return arr[maxIndex][0];
}
//gives the expected answer 6
console.log(lookupFirstNumberFromSecond(
2,
[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]]
));
//gives the expected answer 3
console.log(lookupFirstNumberFromSecond(
2,
[[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]]
));
I'm not entirely sure about what you are trying to achieve but I guess Array.reduce is a pretty elegant solution to get a single value out of an array.
e.g.
var number = 2;
[[1,4],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]]
.reduce(function (a, b) {
return ((!a || b[0] > a[0]) && b[1] === number) ? b : a;
});
Not entirely sure what you're trying to solve either, but if you're trying to get the max value in a n dimensional array, then the most straightforward method is to solve this standardly in a recursive manner
function recurseMax(arr) {
if (Number.isInteger(arr)) {
return arr;
}
else {
answer = 0;
for (let i = 0; i < arr.length; i++) {
answer = answer > recurseMax(arr[i]) ? answer : recurseMax(arr[i]);
}
return answer;
}
}
console.log(recurseMax([1,[3, 5], [5, 6, 7, 10], [2, [3, [500]]]])); //Outputs 500
For each element, either is a number or another possible multidimensional element, so we recursively find its max. This avoids potential overhead from a reduce operation (though I'm not experienced enough to speak with confidence whether or not it is completely faster, not really sure of the optimizations V8 can do on reduce or a plain old recursion loop). Either way, the solution is fairly straightforward.
I am answering the question based on the assumption that you mean that the array can have a max dimension of n.
Related
Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
More formally check if there exists two indices i and j such that :
i != j
0 <= i j < arr.length
arr[i] == 2 * arr[j]
I have solved this question using nested loops and T/C for the approach is obviously O(n^2). But I have seen the solutions using hashmap or set in Javascript which essentially brings the T/C to O(n). But, I am not getting the intuition behind using a set in this question. How is it relevant? If anyone could explain this, please. Thanks.
You could convert your array to an object or set.
Loop through the array, check if element * 2 is in the object/set.
const arr = [1,3,5,7,9,11,14];
const obj = Object.fromEntries(arr.map(el => [el, true])); // O(n)
// obj looks like
//{ "1": true, "3": true, etc}
// loop through arr until we find an element such that twice the element is in obj. Can use O(1) lookups in obj
const result = arr.some(el => obj[el * 2]); // O(n) (usually less)
console.log(result);
How does the following code sort this array to be in numerical order?
var array=[25, 8, 7, 41]
array.sort(function(a,b){
return a - b
})
I know that if the result of the computation is...
Less than 0: "a" is sorted to be a lower index than "b".
Zero: "a" and "b" are considered equal, and no sorting is performed.
Greater than 0: "b" is sorted to be a lower index than "a".
Is the array sort callback function called many times during the course of the sort?
If so, I'd like to know which two numbers are passed into the function each time. I assumed it first took "25"(a) and "8"(b), followed by "7"(a) and "41"(b), so:
25(a) - 8(b) = 17 (greater than zero, so sort "b" to be a lower index than "a"): 8, 25
7(a) - 41(b) = -34 (less than zero, so sort "a" to be a lower index than "b": 7, 41
How are the two sets of numbers then sorted in relation to one another?
Please help a struggling newbie!
Is the array sort callback function called many times during the course of the sort?
Yes
If so, I'd like to know which two numbers are passed into the function each time
You could find out your self with:
array.sort((a,b) => {
console.log(`comparing ${a},${b}`);
return a > b ? 1
: a === b ? 0
: -1;
});
EDIT
This is the output I've got:
25,8
25,7
8,7
25,41
The JavaScript interpreter has some kind of sort algorithm implementation built into it. It calls the comparison function some number of times during the sorting operation. The number of times the comparison function gets called depends on the particular algorithm, the data to be sorted, and the order it is in prior to the sort.
Some sort algorithms perform poorly on already-sorted lists because it causes them to make far more comparisons than in the typical case. Others cope well with pre-sorted lists, but have other cases where they can be "tricked" into performing poorly.
There are many sorting algorithms in common use because no single algorithm is perfect for all purposes. The two most often used for generic sorting are Quicksort and merge sort. Quicksort is often the faster of the two, but merge sort has some nice properties that can make it a better overall choice. Merge sort is stable, while Quicksort is not. Both algorithms are parallelizable, but the way merge sort works makes a parallel implementation more efficient, all else being equal.
Your particular JavaScript interpreter may use one of those algorithms or something else entirely. The ECMAScript standard does not specify which algorithm a conforming implementation must use. It even explicitly disavows the need for stability.
Pairs of values are compared, one pair at a time. The pairs that are compared are an implementation detail--don't assume they will be the same on every browser. The callback can be anything (so you can sort strings or Roman numerals or anything else where you can come up with a function that returns 1,0,-1).
One thing to keep in mind with JavaScript's sort is that it is not guaranteed to be stable.
Deeply Knowledge
If the result is negative a is sorted before b.
If the result is positive b is sorted before a.
If the result is 0 no changes are done with the sort order of the two values.
NOTE:
This code is the view inside of the sort method step by step.
OUTPUT:
let arr = [90, 1, 20, 14, 3, 55];
var sortRes = [];
var copy = arr.slice(); //create duplicate array
var inc = 0; //inc meant increment
copy.sort((a, b) => {
sortRes[inc] = [ a, b, a-b ];
inc += 1;
return a - b;
});
var p = 0;
for (var i = 0; i < inc; i++) {
copy = arr.slice();
copy.sort((a, b) => {
p += 1;
if (p <= i ) {
return a - b;
}
else{
return false;
}
});
p = 0;
console.log(copy +' \t a: '+ sortRes[i][0] +' \tb: '+ sortRes[i][1] +'\tTotal: '+ sortRes[i][2]);
}
To help clarify the behavior of Array#sort and its comparator, consider this naive insertion sort taught in beginning programming courses:
const sort = arr => {
for (let i = 1; i < arr.length; i++) {
for (let j = i; j && arr[j-1] > arr[j]; j--) {
[arr[j], arr[j-1]] = [arr[j-1], arr[j]];
}
}
};
const array = [3, 0, 4, 5, 2, 2, 2, 1, 2, 2, 0];
sort(array);
console.log("" + array);
Ignoring the choice of insertion sort as the algorithm, focus on the hardcoded comparator: arr[j-1] > arr[j]. This has two problems relevant to the discussion:
The > operator is invoked on pairs of array elements but many things you might want to sort such as objects don't respond to > in a reasonable way (the same would be true if we used -).
Even if you are working with numbers, oftentimes you want some other arrangement than the ascending sort that's been baked-in here.
We can fix these problems by adding a comparefn argument which you're familiar with:
const sort = (arr, comparefn) => {
for (let i = 1; i < arr.length; i++) {
for (let j = i; j && comparefn(arr[j-1], arr[j]) > 0; j--) {
[arr[j], arr[j-1]] = [arr[j-1], arr[j]];
}
}
};
const array = [3, 0, 4, 5, 2, 2, 2, 1, 2, 2, 0];
sort(array, (a, b) => a - b);
console.log("" + array);
sort(array, (a, b) => b - a);
console.log("" + array);
const objArray = [{id: "c"}, {id: "a"}, {id: "d"}, {id: "b"}];
sort(objArray, (a, b) => a.id.localeCompare(b.id));
console.log(JSON.stringify(objArray, null, 2));
Now the naive sort routine is generalized. You can see exactly when this callback is invoked, answering your first set of concerns:
Is the array sort callback function called many times during the course of the sort? If so, I'd like to know which two numbers are passed into the function each time
Running the code below shows that, yes, the function is called many times and you can use console.log to see which numbers were passed in:
const sort = (arr, comparefn) => {
for (let i = 1; i < arr.length; i++) {
for (let j = i; j && comparefn(arr[j-1], arr[j]) > 0; j--) {
[arr[j], arr[j-1]] = [arr[j-1], arr[j]];
}
}
};
console.log("on our version:");
const array = [3, 0, 4, 5];
sort(array, (a, b) => console.log(a, b) || (a - b));
console.log("" + array);
console.log("on the builtin:");
console.log("" +
[3, 0, 4, 5].sort((a, b) => console.log(a, b) || (a - b))
);
You ask:
How are the two sets of numbers then sorted in relation to one another?
To be precise with terminology, a and b aren't sets of numbers--they're objects in the array (in your example, they're numbers).
The truth is, it doesn't matter how they're sorted because it's implementation-dependent. Had I used a different sort algorithm than insertion sort, the comparator would probably be invoked on different pairs of numbers, but at the end of the sort call, the invariant that matters to the JS programmer is that the result array is sorted according to the comparator, assuming the comparator returns values that adhere to the contract you stated (< 0 when a < b, 0 when a === b and > 0 when a > b).
In the same sense that I have the freedom to change my sort's implementation as long as I don't breach my specification, implementations of ECMAScript are free to choose the sort implementation within the confines of the language specification, so Array#sort will likely produce different comparator calls on different engines. One would not write code where the logic relies on some particular sequence of comparisons (nor should the comparator produce side effects in the first place).
For example, the V8 engine (at the time of writing) invokes Timsort when the array is larger than some precomputed number of elements and uses a binary insertion sort for small array chunks. However, it used to use quicksort which is unstable and would likely give a different sequence of arguments and calls to the comparator.
Since different sort implementations use the return value of the comparator function differently, this can lead to surprising behavior when the comparator doesn't adhere to the contract. See this thread for an example.
Is the array sort callback function called many times during the course of the sort?
Yes, that's exactly it. The callback is used to compare pairs of elements in the array as necessary to determine what order they should be in. That implementation of the comparison function is not atypical when dealing with a numeric sort. Details in the spec or on some other more readable sites.
Is the array sort callback function called many times during the course of the sort?
Since this is a comparison sort, given N items, the callback function should be invoked on average (N * Lg N) times for a fast sort like Quicksort. If the algorithm used is something like Bubble Sort, then the callback function will be invoked on average (N * N) times.
The minimum number of invocations for a comparison sort is (N-1) and that is only to detect an already sorted list (i.e. early out in Bubble Sort if no swaps occur).
Is the array sort callback function called many times during the course of the sort?
Yes
If so, I'd like to know which two numbers are passed into the function each time.
a: The first element for comparison.
b: The second element for comparison.
In the following example, a will be "2" and b will be "3" in the first iteration
How are the two sets of numbers then sorted in relation to one another?
Elements are sorted according to the return value of the compare function.
greater than 0: sort a after b
less than 0: sort a before b
equal to 0: keep original order of a and b
Here is an example
var arr = [3, 2, 1, 5, 4, 6, 7, 9, 8, 10];
console.log(arr.sort((a, b) => {
console.log(a - b, a, b);
//b-a if sorting in decending order
return a - b;
}));
Im just wondering who can explain the algorithm of this solution step by step. I dont know how hashmap works. Can you also give a basic examples using a hashmap for me to understand this algorithm. Thank you!
var twoSum = function(nums, target) {
let hash = {};
for(let i = 0; i < nums.length; i++) {
const n = nums[i];
if(hash[target - n] !== undefined) {
return [hash[target - n], i];
}
hash[n] = i;
}
return [];
}
Your code takes an array of numbers and a target number/sum. It then returns the indexes in the array for two numbers which add up to the target number/sum.
Consider an array of numbers such as [1, 2, 3] and a target of 5. Your task is to find the two numbers in this array which add to 5. One way you can approach this problem is by looping over each number in your array and asking yourself "Is there a number (which I have already seen in my array) which I can add to the current number to get my target sum?".
Well, if we loop over the example array of [1, 2, 3] we first start at index 0 with the number 1. Currently, there are no numbers which we have already seen that we can add with 1 to get our target of 5 as we haven't looped over any numbers yet.
So, so far, we have met the number 1, which was at index 0. This is stored in the hashmap (ie object) as {'1': 0}. Where the key is the number and the value (0) is the index it was seen at. The purpose of the object is to store the numbers we have seen and the indexes they appear at.
Next, the loop continues to index 1, with the current number being 2. We can now ask ourselves the question: Is there a number which I have already seen in my array that I can add to my current number of 2 to get the target sum of 5. The amount needed to add to the current number to get to the target can be obtained by doing target-currentNumber. In this case, we are currently on 2, so we need to add 3 to get to our target sum of 5. Using the hashmap/object, we can check if we have already seen the number 3. To do this, we can try and access the object 3 key by doing obj[target-currentNumber]. Currently, our object only has the key of '1', so when we try and access the 3 key you'll get undefined. This means we haven't seen the number 3 yet, so, as of now, there isn't anything we can add to 2 to get our target sum.
So now our object/hashmap looks like {'1': 0, '2': 1}, as we have seen the number 1 which was at index 0, and we have seen the number 2 which was at index 1.
Finally, we reach the last number in your array which is at index 2. Index 2 of the array holds the number 3. Now again, we ask ourselves the question: Is there a number we have already seen which we can add to 3 (our current number) to get the target sum?. The number we need to add to 3 to get our target number of 5 is 2 (obtained by doing target-currentNumber). We can now check our object to see if we have already seen a number 2 in the array. To do so we can use obj[target-currentNumber] to get the value stored at the key 2, which stores the index of 1. This means that the number 2 does exist in the array, and so we can add it to 3 to reach our target. Since the value was in the object, we can now return our findings. That being the index of where the seen number occurred, and the index of the current number.
In general, the object is used to keep track of all the previously seen numbers in your array and keep a value of the index at which the number was seen at.
Here is an example of running your code. It returns [1, 2], as the numbers at indexes 1 and 2 can be added together to give the target sum of 5:
const twoSum = function(nums, target) {
const hash = {}; // Stores seen numbers: {seenNumber: indexItOccurred}
for (let i = 0; i < nums.length; i++) { // loop through all numbers
const n = nums[i]; // grab the current number `n`.
if (hash[target - n] !== undefined) { // check if the number we need to add to `n` to reach our target has been seen:
return [hash[target - n], i]; // grab the index of the seen number, and the index of the current number
}
hash[n] = i; // update our hash to include the. number we just saw along with its index.
}
return []; // If no numbers add up to equal the `target`, we can return an empty array
}
console.log(twoSum([1, 2, 3], 5)); // [1, 2]
A solution like this might seem over-engineered. You might be wondering why you can't just look at one number in the array, and then look at all the other numbers and see if you come across a number that adds up to equal the target. A solution like that would work perfectly fine, however, it's not very efficient. If you had N numbers in your array, in the worst case (where no two numbers add up to equal your target) you would need to loop through all of these N numbers - that means you would do N iterations. However, for each iteration where you look at a singular number, you would then need to look at each other number using a inner loop. This would mean that for each iteration of your outer loop you would do N iterations of your inner loop. This would result in you doing N*N or N2 work (O(N2) work). Unlike this approach, the solution described in the first half of this answer only needs to do N iterations over the entire array. Using the object, we can find whether or not a number is in the object in constant (O(1)) time, which means that the total work for the above algorithm is only O(N).
For further information about how objects work, you can read about bracket notation and other property accessor methods here.
You may want to check out this method, it worked so well for me and I have written a lot of comments on it to help even a beginner understand better.
let nums = [2, 7, 11, 15];
let target = 9;
function twoSums(arr, t){
let num1;
//create the variable for the first number
let num2;
//create the variable for the second number
let index1;
//create the variable for the index of the first number
let index2;
//create the variable for the index of the second number
for(let i = 0; i < arr.length; i++){
//make a for loop to loop through the array elements
num1 = arr[i];
//assign the array iteration, i, value to the num1 variable
//eg: num1 = arr[0] which is 2
num2 = t - num1;
//get the difference between the target and the number in num1.
//eg: t(9) - num1(2) = 7;
if(arr.includes(num2)){
//check to see if the num2 number, 7, is contained in the array;
index1 = arr.indexOf(num2);
//if yes get the index of the num2 value, 7, from the array,
// eg: the index of 7 in the array is 1;
index2 = arr.indexOf(num1)
//get the index of the num1 value, which is 2, theindex of 2 in the array is 0;
}
}
return(`[${index1}, ${index2}]`);
//return the indexes in block parenthesis. You may choose to create an array and push the values into it, but consider space complexities.
}
console.log(twoSums(nums, target));
//call the function. Remeber we already declared the values at the top already.
//In my opinion, this method is best, it considers both time complexity and space complexityat its lowest value.
//Time complexity: 0(n)
function twoSum(numbers, target) {
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] === target) {
return [numbers.indexOf(numbers[i]), numbers.lastIndexOf(numbers[j])];
}
}
}
}
Working on exercises to build up my Javascript array skills.
Question is as follows: Write a function biggest_smallest that takes an array of numbers as an input, uses .forEach(), and returns an array containing the smallest number in the zeroth position and the largest number in the first position.
Instead of using forEach(), the only way I could think of doing this was as follows:
var array_of_nums = [7, 8, 120, 60, 10]
function biggest_smallest(array){
var new_array = []
for (var i = 0; i < array.length; i++){
if (array[i] === Math.min.apply(Math, array)){
new_array.unshift(array[i])
} else if (array[i] === Math.max.apply(Math, array)) { ? }
}
return new_array
}
I'm not able to figure out how to place the largest number in index 1 (let alone refactor it using a forEach() method) to solve this exercise complete. I am assuming my method of placing the smallest number in index 0 is correct.
Any help is much appreciated. Thanks.
Assuming this is supposed to work more or less like d3.extent I think the easiest option is just to iterate through with Math.min and Math.max checks:
function smallest_biggest(arr) {
// ditch if no input
if (!array.length) return [];
// start with comparable values
var extent = [Infinity, -Infinity];
arr.forEach(function(val) {
extent[0] = Math.min(extent[0], val);
extent[1] = Math.max(extent[1], val);
});
return extent;
}
Underscore's _.min and _.max functions used to skip the first check, with the incredibly annoying result that _.min([]) === Infinity.
edit My mistake, the question requires forEach iteration, so I suppose there is a need
There really is no need for iteration, you can just use Math.min/Math.max
function biggest_smallest(array){
return [Math.min.apply(null, array), Math.max.apply(null, array)];
}
I'd say first you need to find two variables: a (minimum value in the array) and b (the maximum). Then, outside the loop (that you can implement using foreach or the regular syntax) you just push the two values to the resulting array:
new_array.push(a);
new_array.push(b);
return new_array;
var array_of_nums = [7, 8, 120, 60, 10]
function smallest_biggest(arr) {
var new_array = []
arr.forEach(function() {
new_array[0] = Math.min.apply(Math, arr)
new_array[1] = Math.max.apply(Math, arr)
})
return new_array
}
smallest_biggest(array_of_nums)
function largestInEach(arr) {
var resultArray = [],
highestValue = 0;
for (var i = 0; i < arr.length; i++) {
highestValue = arr[i].reduce(function(a, b){
return a >= b ? a : b;
});
resultArray.push(highestValue);
}
return resultArray;
}
Can someone please explain this code.
The rest of the code is very clear to me, but I have difficulty understanding the reduce function and its application.
I agree with most of the other comments that you should search more and do self learning.
However, I know it is sometimes hard to find the exact info on how things work. So ill explain this to you.
Now coming to your code.
https://jsfiddle.net/Peripona/ppd4L9Lz/
It contains an array of arrays where you at the end create a resulted array with highest or lowest value elements from all the sub arrays.
like you got
var arry = [[1,2,3],[2,3,4],[20,-2,3]]
talking in layman terms...
you got one array if you sort or reduce an array of integers, it might not always generate what you
say for example if you got this data
var ar = [1,3,34,11,0,13,7,17,-2,20,-21]
and if you do normal ar.sort() to get the sorted values
you would expect something like this... as output
" [-21, -2, 0, 1, 3, 7, 11, 13, 17, 20, 34] "
but on the contrary you would get the output like this..
" [-2, -21, 0, 1, 11, 13, 17, 20, 3, 34, 7] "
Now you wonder... why this strange behavior and how does it matter anyhow to my Question..
It Does matter..
Cuz this is what you need to do to get the right output..
The way sort function is written has to work for for String and other types as well. so they convert data into other formats when doing comparison on sort.
So all in all if you pass a function inside and specify that you need the in ascending order that is a-b..
Descending order that is b-a..
ar.sort(function(a,b){return a-b;})
Now coming to another part that is Reduce this function takes a function argument and get you the highest or the lowest value from the array.
therefore if you do..
ar.reduce(function(a,b){return a>=b ? b : a})
will give you -21 as the output..
and if you do
ar.reduce(function(a,b){return a>=b ? a : b})
It will give you : 34
So this function will take multidimensional arrays where each array contains some digits and this function will get you the highest from all those arrays..
I hope this Explains everything.
Reduce function allows you to go through each item in an array, where you will be able to see previous array value, and current array value, in your case:
a = previous value,
b = current value,
-(not in there)-
i = index,
currArray = the array you are working with.
and in your code you are comparing and returning if your previous value is greater than or equal to current value.
a >= b ? a : b;
Conditional (ternary) Operator which is (condition ? do this : or this ) -> Think of it like a if statement
If(a >= b){
return a
}else{
return b
}
see Conditional (ternary) Operator
Also your 'arr' could be multi dimensional array. forexample Trying the following code on http://plnkr.co/edit/?p=preview
hit f12 for developer tools and look at console for results.
var arr = [[1,2],[4,3],[5,23,52]];
var resultArray = [],
var highestValue;
for (var i = 0; i < arr.length; i++) {
highestValue = arr[i].reduce(function(a, b){
return a >= b ? a : b;
});
resultArray.push(highestValue);
}
console.log(resultArray);
You result array contains [2, 4, 52].
I hope this helps.
JS reduce method is applied against two values of array and reduce these two values of array ( a and b) into one (c) based on defined condition (return c = a+b ).
Here in your case the condition was which among two is greater (a>b?a:b).