0

I'm trying to eliminate the minimum and maximum values from the below array and create 2 new arrays without the maximum and minimum values

array = [4, 6, 7, 8, 9]
const indOmin = 0,
  indOm = 5

minArr = arr
maxArr = arr

minArr.forEach(cur => {
  if (arr.indexOf(cur) === indOmin) {
    minArr.splice(indOmin, 1)
  }
})

maxArr.forEach(cur => {
  if (arr.indexOf(cur) === indOm) {
    maxArr.splice(indOm, 1)
  }
})

When I use...

console.log(minArr)
console.log(maxArr)

...then in both cases it returns [6, 7, 8, 9].

But instead of...

minArr = arr
maxArr = arr

...if I use...

minArr = arr.map(cur => cur = cur)
maxArr = arr.map(cur => cur = cur)

... then the arrays return expected values.

[6, 7, 8, 9]
[4, 6, 7, 8]

Please help me understand why it doesn't work when I explicitly use the = operator (minArr = arr).

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Abdul Qadir
  • 11
  • 1
  • 3
  • 1
    Those `forEach` and `indexOf` calls make no sense. If you're looping, you already know the index, no need to search for it. And since you're given the indices of min and max anyway, you don't need to do any looping at all - just call `splice` right away! – Bergi May 30 '20 at 16:23
  • Also, `arr.map(cur => cur = cur)` is weird because the `cur = cur` does nothing (and just returns `cur`). It's the same as `arr.map(cur => cur)`. – CherryDT May 30 '20 at 16:24

1 Answers1

0

Change

minArr=arr; maxArr=arr;

To

minArr=[...arr]; maxArr=[...arr];

It doesn't work because array doesn't copy with = you had reference of same array in both minarr and maxarr.

Aakash Garg
  • 10,649
  • 2
  • 7
  • 25