How to get the index of highest value containing negative number from an array in javascript? [duplicate]

You could use reduce method and check if current element is < 0 and greater then accumulator value.

var arr = [-7, -5, -4, -2, 1, 3, 9];
const result = arr.reduce((r, e) => {
  if(e < 0 && r < e) r = e;
  return r;
})

console.log(result)

To get index you could use one object as {value, index} as accumulator and get index.

var arr = [-7, -5, -4, -2, 1, 3, 9];
const result = arr.reduce((r, val, index) => {
  if(index == 0 || val < 0 && r.val < val) r = {val, index}
  return r;
}, 0).index

console.log(result)

Browse More Popular Posts

Leave a Comment