SmartestVEGA
SmartestVEGA

Reputation: 8889

Remove range of numeric from javascript array

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);
        }

    }
});

Upvotes: 1

Views: 743

Answers (2)

disrvptor
disrvptor

Reputation: 1612

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.

Upvotes: 1

hmnzr
hmnzr

Reputation: 1430

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

Upvotes: 2

Related Questions