user1439488 user1439488 - 2 months ago 6
Node.js Question

Trying to match values in two arrays and only delete if there is an exact match for part of the value

I receive two arrays of IP addresses, which are formatted differently. Any values in the IPs array should be deleted from the addresses array - but only if the IPs match exactly. I've written the below, but the issue is that for example, 192.168.0.1 will match 192.168.0.11 and then subsequently delete 192.168.0.11 from the addresses array which is not a valid result. The addresses array needs to be returned in the same format as it is received. Any help please? :)

var addresses = [{
Value : '192.168.0.11'
}, {
Value : '52.210.29.181'
}, {
Value : '52.210.128.97'
}
];

var IPs = ['192.168.0.1', '52.210.128.97'];

console.log('Before:', addresses);

for (var x = 0; x < IPs.length; x++) {

for (var key in addresses) {
var address = JSON.stringify(addresses[key]);

if (address.indexOf(IPs[x]) > -1){ //if the IP is a substr of address

console.log('matched, so delete', addresses[key]);
var index = addresses.indexOf(addresses[key]); //find the index of IP to be deleted then delete it
addresses.splice(index, 1);

}


}
}

console.log('After', addresses);

Answer

Using clean approach of Array.filter :

    var addresses = [{
       Value: '192.168.0.11'
       },
      {
       Value: '52.210.29.181'
      }, {
      Value: '52.210.128.97'
    }];
    
    var IPs = ['192.168.0.1', '52.210.128.97'];
    
    var filterdAddresses = addresses.filter(function (item) {
        var match = false;
        IPs.forEach(function (ip) {
            if (item.Value == ip) {
                match = true;
            }
    
        });
        return !match;
    
    });
    
    console.log(filterdAddresses);

Comments