1

I have an array of [2016,2017,2018,2019]

I have a range fromValue 2017 toValue 2017

Hence resulting array should be [2017] because of i need to remove whatever out of range between fromValue and toValue.

I have written code below which is only removing 2016 and 2018 but not 2019.

Whats wrong i am doing , is there any beter way to do this?

gNodeIDs.forEach(function (item) {              
    alert("Before if" + item);
    if (item >= fromValue) {
        if (item <= toValue) {                        
        }
        else
        {
            alert("removing" + item);
            var index = test.indexOf(item);
            if (index >= 0) {
                test.splice(index, 1);
            }
        }
    }
    else {
        alert("removing" + item);
        var index = test.indexOf(item);
        if (index >= 0) {
            test.splice(index, 1);
        }

    }
});
1
  • how? to use filter? Commented May 30, 2017 at 13:28

2 Answers 2

2

Use Array.prototype.filter to achieve this:

var result = gNodeIDs.filter(function(item) { return item >= fromValue && item <= toValue });

result array with contain all matching items

Sign up to request clarification or add additional context in comments.

2 Comments

Probably not a problem, but worth mentioning this was added in JavaScript 1.6. However, there is a polyfill if you're worried about it developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@SmartestVEGA glad it helped, please, do not forget to accept the answer ;)
1

Using Array.prototype.filter is the correct answer, but it's worth noting you are not using the forEach function correctly. According to Array.prototype.forEach

The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the array after the call to forEach() begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped - see example below.

If you wanted to use the forEach function then you should use 2 copies of the same array, the first for iterating and the second for removal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.