A question on JavaScript .reduce method's accumulator - javascript

I was working on this problem to create a function using a reduce method that will get the max number in an array.
The instructor's answer is:
const numbers = [1, 2, 3, 4, 4, 5, 1, 3, 4];
const max = getMax(numbers);
console.log(max);
function getMax(array) {
if (array.length === 0) return undefined;
return array.reduce((accumulator, current) => {
return (accumulator > current) ? accumulator : current
});
I tried something like this:
return array.reduce((accumulator, current) => {
if (accumulator < current)
console.log(accumulator, current);
return accumulator = current;
});
I added console.log (accumulator, current) because I wanted to see what's going on with my code. The log shows as follows:
console.log of my code
1 2
2 3
3 4
4 5
1 3
3 4
4
Question 1. I'd like to know why my function didn't give the right output (it returned 4, not the correct output 5). Shouldn't "accumulator" stay 5 when it is assigned as 5 during the loop?
Question 2. Why do I need to return (or add return in front of) array in the function, when there is already a return below the if statement?

You didn't use { ... } after your if statement, so only the first line console.log(...) is happening when the condition is met. The accumlator = current line always happens for each iteration. You must use return when using imperative style if statement. However you can skip return when using functional style expressions, ie (accumulator, current) => accumulator < current ? current : accumulator which says "if accumulator is less than current, return current, else return accumulator".
Consider this decomposed program. When we see max as an independent function, it helps us see precisely the type of function reduce is expecting -
const max = (a = 0, b = 0) =>
a < b // if a is less than b
? b // return b
: a // otherwise return a
const getMax = (numbers = []) =>
numbers.length === 0 // if numbers.length is zero
? undefined // return undefined
: numbers.reduce(max) // otherwise return reduction
console.log(getMax([1, 2, 3, 4, 4, 5, 1, 3, 4]))
// 5
console.log(getMax([]))
// undefined
console.log(getMax())
// undefined
We can see reduce is produces the following computation -
// given
[1, 2, 3, 4, 4, 5, 1, 3, 4]
// starting with the first two
r = max(1, 2)
// then the next number
r = max(r, 3)
// then the next number
r = max(r, 4)
// then the next number
r = max(r, 4)
Or without intermediate r = ... -
max(max(max(max(max(max(max(max(1, 2), 3), 4), 4), 5), 1), 3), 4)
We could write getMax without reduce, if we wanted -
const max = (a = 0, b = 0) =>
a < b
? b
: a
const getMax = (numbers = []) =>
numbers.length === 0 // without any numbers,
? undefined // there can be no max.
: numbers.length === 1 // if we only have one,
? numbers[0] // we already know max.
: max(numbers[0], getMax(numbers.slice(1))) // else
console.log(getMax([1, 2, 3, 4, 4, 5, 1, 3, 4]))
// 5
console.log(getMax([]))
// undefined
console.log(getMax())
// undefined
Or maybe you haven't learned slice yet. You can use an array index, i, to step thru your array -
const max = (a = 0, b = 0) =>
a < b
? b
: a
const getMax = (numbers = [], i = 0) =>
numbers.length === 0 // without any numbers,
? undefined // there can be no max.
: i + 1 >= numbers.length // if the next i is not in bounds,
? numbers[i] // this is the last number
: max(numbers[i], getMax(numbers, i + 1)) // else
console.log(getMax([1, 2, 3, 4, 4, 5, 1, 3, 4]))
// 5
console.log(getMax([]))
// undefined
console.log(getMax())
// undefined
Destructuring assignment can be used as well -
const max = (a = 0, b = 0) =>
a < b
? b
: a
const getMax = ([ num, ...more ] = []) =>
more.length === 0
? num
: max(num, getMax(more))
console.log(getMax([1, 2, 3, 4, 4, 5, 1, 3, 4]))
// 5
console.log(getMax([]))
// undefined
console.log(getMax())
// undefined
This might show you how you can invent your own reduce -
const max = (a = 0, b = 0) =>
a < b
? b
: a
const reduce = (f, a = [], i = 0) =>
a.length === 0 // without any numbers,
? undefined // there can be no reduction.
: i + 1 >= a.length // if the next i is not in bounds,
? a[i] // this is the last element
: f(a[i], reduce(f, a, i + 1)) // else
const getMax = (numbers = []) =>
reduce(max, numbers) // <-- our reduce!
console.log(getMax([1, 2, 3, 4, 4, 5, 1, 3, 4]))
// 5
console.log(getMax([]))
// undefined
console.log(getMax())
// undefined

Try use Math.max method:
const numbers = [1, 2, 3, 4, 4, 5, 1, 3, 4]
numbers.reduce((acc, rec) => Math.max(acc, rec))
//5
or
function max(numbers) {
return list.reduce((acc, rec) => acc > rec ? acc : rec)
}
if you need find max value without Math.max.

Related

Group the consecutive numbers from an array with series of numbers which are greater than 2 into subarrays using javascript

Given an array A = [1,2,3,5,6,7,8,10,0,1,1,2,4,10,6,7,3], group the consecutive elements which are greater than 2 in to sub-arrays.
The desired output is result = [[2,3,5,6,7,8,10],[2,4,10,6,7,3]].
Example: A = [1,2,3,5,6,7,8,10,0,1,1,2,4,10,6,7,3]
Output: result = [[2,3,5,6,7,8,10],[2,4,10,6,7,3]]
Could anyone help with this question?
I have tried:
const a = [0, 1, 2, 5, 6, 9];
const result = a.reduce((acc, current) =>
const lastSubArray = acc[acc.length - 1];
console.log(`${acc}-${current}`)
console.log(lastSubArray[lastSubArray.length - 1]);
if (current >2 && lastSubArray[lastSubArray.length - 1]>2) {
acc.push(current);
}
acc[acc.length - 1].push(current);
console.log(acc);
return acc;
}, []);
console.log(result);
You can use a global variable to keep track of the indexes so that it's possible to detect when exists a gap between two numbers, which allows you to add another array. In combination, using ternary operators can make the code cleaner to test for conditions.
const arr = [1, 2, 3, 5, 6, 7, 8, 10, 0, 1, 1, 2, 4, 10, 6, 7, 3];
let lastIdx = -1
const results = arr.reduce((acc, current, idx) =>
(
current > 2 ? (
lastIdx + 1 === idx && acc.length ?
(
lastIdx = idx,
acc[acc.length - 1].push(current),
acc
)
:
(
lastIdx = idx,
[...acc, [current]]
)
) : acc
)
, [])
console.log(results);

how to get sum of odd, even numbers using Array.reduce method?

how to get sum of odd, even using reduce method, i have done as show in below code but returning undefined , #js-beginner
//code below
nums= [1,2,3,4,5,6,7,8,9]
function getOddEvenSum(numbers){
let{even,odd} = numbers.reduce((acc, cuu) => cuu%2 === 0?acc.even + cuu:acc.odd+cuu,{even:0, odd:0})
return {even, odd}
}
console.log(getOddEvenSum(nums)
//output i am getting below
{even:undefined, odd:undefined}
The value that you return from your reduce callback will be the value of acc upon the next invocation/iteration of your array of numbers. Currently, your acc starts off as an object, but as you're only returning a number from your first iteration, all subsequent iterations will use a number as acc, which don't have .even or .odd properties. You could instead return a new object with updated even/odd properties so that acc remains as an object through all iterations:
const nums = [1,2,3,4,5,6,7,8,9];
function getOddEven(numbers){
return numbers.reduce((acc, cuu) => cuu % 2 === 0
? {odd: acc.odd, even: acc.even + cuu}
: {even: acc.even, odd: acc.odd+cuu},
{even:0, odd:0});
}
console.log(getOddEven(nums));
You can use Array.prototype.reduce like this:
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const [odds, evens] = nums.reduce(
([odds, evens], cur) =>
cur % 2 === 0 ? [odds, evens + cur] : [odds + cur, evens],
[0, 0]
);
console.log(odds);
console.log(evens);
This is not how the syntax of reduce works. One possible implementation:
function getOddEven(nums) {
return nums.reduce(
({odd, even}, num) => num % 2 === 0 ?
{odd, even: even + num} :
{odd: odd + num, even},
{odd: 0, even: 0},
);
}
I would argue that this is not very clear. Since performance is probably not critical, a clearer alternative would be:
function getOddEven(nums) {
return {
odd: nums.filter(num => num % 2 == 1).reduce((acc, num) => acc + num),
even: nums.filter(num => num % 2 == 0).reduce((acc, num) => acc + num),
};
}
based on your code, you need to return acc
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
function getOddEven(numbers) {
let {
even,
odd
} = numbers.reduce((acc, cuu) => {
if(cuu%2 == 0)
{
acc.even += cuu
}
else{
acc.odd += cuu
}
return acc
},
{
even: 0,
odd: 0
})
return {
even,
odd
}
}
console.log(getOddEven(nums))

return "even" if others numbers are odd and "odd" the others number are even javascript

I have 2 questions, how can I get value instead of value inside array and how can I make this code shorter and declarative.
arr = [16, 4, 11, 20, 2]
arrP = [7, 4, 11, 3, 41]
arrTest = [2, 4, 0, 100, 4, 7, 2602, 36]
function findOutlier(arr) {
const isPair = (num) => num % 2 === 0
countEven = 0
countOdd = 0
arr1 = []
arr2 = []
const result = arr.filter((ele, i) => {
if (isPair(ele)) {
countEven++
arr1.push(ele)
} else {
countOdd++
arr2.push(ele)
}
})
return countEven > countOdd ? arr2 : arr1
}
console.log(findOutlier(arrTest))
Filtering twice may be more readable.
even = arr.filter((x) => x % 2 == 0);
odd = arr.filter((x) => x % 2 == 1);
if (even.length > odd.length) {
return even;
} else {
return odd;
}
If you're looking to do this with one loop, consider using the array reduce method to put each number into an even or odd bucket, and then compare the length of those buckets in your return:
function findOutlier(arr) {
const sorted = arr.reduce((acc, el) => {
acc[el % 2].push(el);
return acc;
},{ 0: [], 1: [] })
return sorted[0].length > sorted[1].length ? sorted[1] : sorted[0];
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(findOutlier(arr));
Note that this does not handle when the arrays are the same length gracefully (right now it'll just return the odd array).
You could take an object with the wanted part for collecting and add a short circuit if one of the types has a count of one and the others have a count greater than one.
const
isPair = num => num % 2 === 0,
findOutlier = array => {
count = { true: [], false: [] };
for (const value of array) {
count[isPair(value)].push(value);
if (count.true.length === 1 && count.false.length > 1) return count.true[0];
if (count.false.length === 1 && count.true.length > 1) return count.false[0];
}
};
console.log(...[[16, 4, 11, 20, 2], [7, 4, 11, 3, 41], [2, 4, 0, 100, 4, 7, 2602, 36]].map(findOutlier));
Here is an solution that selects the even or odd array based on the modulo result.
function findOutlier(integers) {
const even = [], odd = [], modulos = [even, odd];
for (const integer of integers) {
modulos[Math.abs(integer % 2)].push(integer);
}
return even.length > odd.length ? odd : even;
}
console.log(findOutlier([2, 4, 0, 100, 4, 7, 2602, 36]));
You unfortunately do need Math.abs() to handle negative values, because -3 % 2 == -1.
See: JavaScript % (modulo) gives a negative result for negative numbers
However the name findOutlier lets me assume there is only a single outlier within the provided list. If this is the case you can optimize the algorithm.
function findOutlier(integers) {
// With less than 3 integers there can be no outlier.
if (integers.length < 3) return;
const isEven = (integer) => integer % 2 == 0;
const isOdd = (integer) => !isEven(integer);
// Determine the outlire based on the first 3 elements.
// If there are 0 or 1 integers even, the outlire is even.
// if there are 2 or 3 integers even, the outlier is odd.
const outlier = integers.slice(0, 3).filter(isEven).length < 2
? isEven
: isOdd;
return integers.find(outlier);
}
console.log(findOutlier([2, 4, 0, 100, 4, 7, 2602, 36]));
You can do this without creating intermediate arrays by simply comparing each element to its neighbors and returning that element if it is different to both, or undefined if no outliers are found. This returns in the same iteration in which the outlier is first encountered, and returns the value itself and not an array.
function findOutlier(array) {
const
len = array.length,
isEven = (n) => n % 2 === 0;
for (const [i, value] of array.entries()) {
let
prev = array[(i-1+len)%len], // loop around if < 0 (first element)
next = array[(i+1)%len]; // loop around if >= length (last element)
if (isEven(value) !== isEven(prev) && isEven(value) !== isEven(next)) {
return value;
}
}
return undefined;
}
const arrays = [[16, 4, 11, 20, 2], [7, 4, 11, 3, 41], [2, 4, 0, 100, 4, 7, 2602, 36]]
console.log(...arrays.map(findOutlier));
Now that OP clarified the requirements (at least in a comment) this allows a different approach:
function findOutlier(array) {
let odd = undefined, even = undefined;
for (let i of array) {
let isEven = i % 2 == 0;
if (odd !== undefined && even !== undefined)
return isEven ? odd : even;
if (isEven) even = i;
else odd = i;
}
if (odd !== undefined && even !== undefined)
return array[array.length-1];
}
console.log(findOutlier([2,4,6,8,10,5]))
The algorithm will iterate the array, and store the lastest found odd and even numbers, respectively.
If we discovered both an odd and an even number already, with the current number we can decide, which of them is the outlier: If the current number is even, it's at least the second even number we found. Thus, the found odd number must be the outlier. The same applies vice versa if the current number is odd. The special case, if the outlier is the last element of the array, is checked with an additional condition after the loop.
If all numbers are odd or even (ie there is no outlier) this function will return undefined. This algorithm does not throw an error, if the preconditions are not met, ie if there is more than one outlier.

How to find elements in array JavaScript where array[i] = i?

I need to find elements in an array of numbers where arr[i] === i, meaning the element must be equal to the array index.
They must be found with using recursion, not just by cycle.
I would be very thankful, if someone help, because I've spent many hours and can't do anything.
I've tried to use Binary Search but it doesn't work. In the end I've got only the empty array.
function fixedPointSearch(arr, low, high) {
let middle = Math.floor((high - low) / 2);
console.log( low, high, middle )
let arrRes = [];
if (arr[middle] === middle)
{ arrRes.push(arr[middle]); }
else if (arr[middle] > middle)
{ fixedPointSearch(arr, middle + 1, high); }
else
{ fixedPointSearch(arr, low, middle - 1); }
return arrRes;
}
const arr1 = [-10, -3, 2, 3, 6, 7, 8, 9, 10, 12, 16, 17];
console.log(fixedPointSearch(arr1, 0, arr1.length - 1));
To do this recursively, you presumably want to recurse on smaller and smaller arrays, but that means you need to also update the index you're checking on each call. One of the simplest ways to do this is just to include an index in the parameters to your function and increment it on each recursive call. This is one way to do so:
const fixedPointSearch = ([x, ...xs] = [], index = 0) =>
x == undefined
? []
: [... (x === index ? [x] : []), ... fixedPointSearch (xs, index + 1)]
console .log (
fixedPointSearch([-10, -3, 2, 3, 6, 7, 8, 9, 10, 12, 16, 17])
)
It's debatable whether that version or the following one is easier to read, but they are doing essentially the same thing:
const fixedPointSearch = ([x, ...xs] = [], index = 0) =>
x == undefined
? []
: x === index
? [x, ... fixedPointSearch (xs, index + 1)]
: // else
fixedPointSearch (xs, index + 1)
There is a potential problem, though. Running this over a large array, we could hit the recursion depth limit. If the function were tail-recursive, that problem would simply vanish when JS engines perform tail-call optimization. We don't know when that will be, of course, or even it it will actually ever happen, even though it's been specified for five years. But it sometimes makes sense to write to take advantage of it, on the hope that it will one day become a reality, especially since these will still work as well as the non-tail-call version.
So a tail-recursive version might look like this:
const fixedPointSearch = ([x, ...xs] = [], index = 0, res = []) =>
x == undefined
? res
: fixedPointSearch (xs, index + 1, x === index ? [...res, x] : res)
You can solve this w/o additional temporary arrays and parameters, by simply shortening the array in each step:
const myArray = [0, 5, 2, 4, 7, 9, 6];
function fixedPointSearch(arrayToTest) {
if (arrayToTest.length === 0) {
return [];
}
const lastIndex = arrayToTest.length - 1;
const lastItem = arrayToTest[lastIndex];
const remainingItems = arrayToTest.slice(0, lastIndex);
return lastItem === lastIndex
? [...fixedPointSearch(remainingItems), lastItem]
: fixedPointSearch(remainingItems);
}
console.log(fixedPointSearch(myArray));
If you want to find all the elements you should start from the beginning of the array, not the middle and loop through all the indexes.
The idea is for the recursion is to define the end condition.
Then you check if arr[i] === i to update the results array.
Then you make the recursive call with the index incremented and with the updated results array.
function fixedPointSearch(arr, i, results) {
// End condition of the recursion
if (i === arr.length - 1 || arr.length === 0) {
return results;
}
if (arr[i] === i) {
results.push(i);
}
// Recursive call
return fixedPointSearch(arr, i + 1, results);
}
const arr1 = [-10, -3, 2, 3, 6, 7, 8, 9, 10, 12, 16, 17];
console.log(fixedPointSearch(arr1, 0, []));
console.log(fixedPointSearch([], 0, []));
console.log(fixedPointSearch([9, 8, 7], 0, []));
The idiomatic solution in JavaScript uses Array.prototype.filter -
const run = (a = []) =>
a.filter((x, i) => x === i)
console.log(run([ 0, 1, 2, 3, 4, 5 ])) // [0,1,2,3,4,5]
console.log(run([ 3, 3, 3, 3, 3, 3 ])) // [3]
console.log(run([ 7, 1, 7, 3, 7, 5 ])) // [1,3,5]
console.log(run([ 9, 9, 9, 9, 9, 9 ])) // []
Above it should be clear that recursion isn't required for the job. But there's nothing stopping you from using it, if you wish -
const filter = (test = identity, a = [], i = 0) =>
{ /* base */
if (i >= a.length)
return []
/* inductive: i is in bounds */
if (test(a[i], i))
return [ a[i], ...filter(test, a, i + 1) ]
/* inductive: i is in bounds, a[i] does not pass test */
else
return filter(test, a, i + 1)
}
const run = (a = []) =>
filter((x, i) => x === i, a)
console.log(run([ 0, 1, 2, 3, 4, 5 ])) // [0,1,2,3,4,5]
console.log(run([ 3, 3, 3, 3, 3, 3 ])) // [3]
console.log(run([ 7, 1, 7, 3, 7, 5 ])) // [1,3,5]
console.log(run([ 9, 9, 9, 9, 9, 9 ])) // []
For recursion, you'll need an end condition. Something like
const findElementValueIsPositionInarray = arr => {
let results = [];
const find = i => {
if (arr.length) { // as long as arr has values
const value = arr.shift(); // get value
results = i === value // check it
? results.concat(value)
: results;
return find(i+1); // redo with incremented value of i
}
return results;
};
return find(0);
}
console.log(findElementValueIsPositionInarray([2,3,4,3,9,8]).join());
console.log(findElementValueIsPositionInarray([2,3,4,91,9,8]).join());
console.log(findElementValueIsPositionInarray([0,1,2,87,0,5]).join());
.as-console-wrapper { top: 0; max-height: 100% !important; }
I don't know why you want it through recursion:-
But anyway following should help you:-
let ans = [];
function find(arr,index,ans)
{
if(index==arr.length-1)
{
if(arr[index]==index){
ans.push(arr[index])
}
return;
}
if(arr[index]==index){
ans.push(arr[index])
}
find(arr,index+1,ans);
}
const arr1 = [-10, -3, 2, 3, 6, 7, 8, 9, 10, 12, 16, 17];
find(arr1,0,ans);
console.log(ans);

Finding the local maxima in a 1D array

Is there an easy way to find the local maxima in a 1D array?
Let's say I have an array:
[ 0,
1,
10, <- max
8, <- (ignore)
3,
0,
0,
4,
6, <- (ignore)
10, <- max
6, <- (ignore)
1,
0,
0,
1,
4, <- max
1,
0 ]
I want it to find the 10s and the 4, but ignore the 8 & 6, since those are next to 10s. Mathematically, you could just find where derivative is equal to zero if it were a function. I'm not too sure how to do this in Javascript.
This will return an array of all peaks (local maxima) in the given array of integers, taking care of the plateaus as well:
function findPeaks(arr) {
var peak;
return arr.reduce(function(peaks, val, i) {
if (arr[i+1] > arr[i]) {
peak = arr[i+1];
} else if ((arr[i+1] < arr[i]) && (typeof peak === 'number')) {
peaks.push(peak);
peak = undefined;
}
return peaks;
}, []);
}
findPeaks([1,3,2,5,3]) // -> [3, 5]
findPeaks([1,3,3,3,2]) // -> [3]
findPeaks([-1,0,0,-1,3]) // -> [0]
findPeaks([5,3,3,3,4]) // -> []
Note that the first and last elements of the array are not considered as peaks, because in the context of a mathematical function we don't know what precedes or follows them and so cannot tell if they are peaks or not.
maxes = []
for (var i = 1; i < a.length - 1; ++i) {
if (a[i-1] < a[i] && a[i] > a[i+1])
maxes.push(a[i])
}
This code finds local extrema (min and max, where first derivation is 0, and ), even if following elements will have equal values (non-unique extrema - ie. '3' is choosen from 1,1,1,3,3,3,2,2,2)
var GoAsc = false; //ascending move
var GoDesc = false; //descending move
var myInputArray = [];
var myExtremalsArray = [];
var firstDiff;
for (index = 0; index < (myArray.length - 1); index++) {
//(myArray.length - 1) is because not to exceed array boundary,
//last array element does not have any follower to test it
firstDiff = ( myArray[index] - myArray[index + 1] );
if ( firstDiff > 0 ) { GoAsc = true; }
if ( firstDiff < 0 ) { GoDesc = true; }
if ( GoAsc === true && GoDesc === true ) {
myExtremalsArray.push(myArray[index]);
GoAsc = false ;
GoDesc = false;
//if firstDiff > 0 ---> max
//if firstDiff < 0 ---> min
}
}
The two situations are when you have a peak, which is a value greater than the previous and greater than the next, and a plateau, which is a value greater than the previous and equal to the next(s) until you find the next different value which must me less.
so when found a plateau, temporary create an array from that position 'till the end, and look for the next different value (the Array.prototype.find method returns the first value that matches the condition ) and make sure it is less than the first plateau value.
this particular function will return the index of the first plateau value.
function pickPeaks(arr){
return arr.reduce( (res, val, i, self) => {
if(
// a peak when the value is greater than the previous and greater than the next
val > self[i - 1] && val > self[i + 1]
||
// a plateau when the value is greater than the previuos and equal to the next and from there the next different value is less
val > self[i - 1] && val === self[i + 1] && self.slice(i).find( item => item !== val ) < val
){
res.pos.push(i);
res.peaks.push(val);
}
return res;
}, { pos:[],peaks:[] } );
}
console.log(pickPeaks([3,2,3,6,4,1,2,3,2,1,2,3])) //{pos:[3,7],peaks:[6,3]}
console.log(pickPeaks([-1, 0, -1])) //{pos:[1],peaks:[0]}
console.log(pickPeaks([1, 2, NaN, 3, 1])) //{pos:[],peaks:[]}
console.log(pickPeaks([1, 2, 2, 2, 1])) //{pos: [1], peaks: [2]} (plateau!)
How about a simple iteration?
var indexes = [];
var values = [0,1,10,8,3,0,0,4,6,10,6,1,0,0,1,4,1,0];
for (var i=1; i<values.length-1; i++)
if (values[i] > values[i-1] && values[i] > values[i+1])
indexes.push(i);
more declarative approach:
const values = [3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3];
const findPeaks = arr => arr.filter((el, index) => {
return el > arr[index - 1] && el > arr[index + 1]
});
console.log(findPeaks(values)); // => [6, 3]
A Python implementation, with a couple of points
Avoids using a reduce to make it easier to see the algorithm
First and last items are considered peaks (this can be a requirement, e.g. in interviews)
All values in the plateau are added
Can start or end on an plateau
def findPeaks(points: List[int]) -> List[int]:
peaks, peak = [], []
if points[0] >= points[1]: # handle first
peak.append(points[0])
for i in range(1, len(points)):
prv = points[i - 1]
cur = points[i]
if cur > prv: # start peak
peak = [cur]
elif cur == prv: # existing peak (plateau)
peak.append(cur)
elif cur < prv and len(peak): # end peak
peaks.extend(peak)
peak = []
if len(peak) and len(peak) != len(points): # ended on a plateau
peaks.extend(peak)
return peaks
if __name__ == "__main__":
print(findPeaks([1, 2, 3, 4, 5, 4, 3, 2, 1])) # [5]
print(findPeaks([1, 2, 1, 2, 1])) # [2, 2]
print(findPeaks([8, 1, 1, 1, 1, 1, 9])) # [0, 6]
print(findPeaks([1, 1, 1, 1, 1])) # []
print(findPeaks([1, 6, 6, 6, 1])) # [6, 6, 6]
const values = [3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3];
const findMinimas = arr => arr.filter((el, index) => {
return el < arr[index - 1] && el < arr[index + 1]
});
console.log(findMinimas(values)); // => [2, 1, 1]
const findMinimumIndices = arr => arr.map((el, index) => {
return el < arr[index - 1] && el < arr[index + 1] ? index : null
}).filter(i => i != null);
console.log(findMinimumIndices(values)); // => [1, 5, 9]

Categories