Ad
Get Unique Values From Array Within A Range?
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad