Ad

Get Unique Values From Array Within A Range?

- 1 answer

I have an array, I need to return new array with the values in range (from a to b) BUT! I want to return without duplicates. I wrote the script below but it doesn't work properly.

let arr = [3, 9, 10, 23, 100, 100, 23, 4, 10, 13, 13];
let newArr = [];
let funcFilter = function(arr, a, b) {
  for(let i = 0; i< arr.length; i++) {
  if(arr[i] >= a && arr[i] <= b ) {
  if(arr.indexOf(arr[i]) !== -1)
   newArr.push(arr[i]);
}
}
return newArr;
}
console.log(funcFilter(arr, 3, 20))
Ad

Answer

Ypu need to check value in newArr,so arr.indexOf(arr[i]) !== -1 needs to be change to newArr.indexOf(arr[i]) == -1

let arr = [3, 9, 10, 23, 100, 100, 23, 4, 10, 13, 13];
let newArr = [];
let funcFilter = function(arr, a, b) {
  for(let i = 0; i< arr.length; i++) {
    if(arr[i] >= a && arr[i] <= b ) {
       if(newArr.indexOf(arr[i]) == -1)
         newArr.push(arr[i]);
       }
   }
return newArr;
}
console.log(funcFilter(arr, 3, 20))

Ad
source: stackoverflow.com
Ad