Reputation: 21
hi i've got an array i made from a txt file. each element of the array is something like this:
examplea A 10.20.5.197
exampleb A 10.10.7.178
examplec A 10.20.75.116
exampled A 10.20.90.170
i wanna loop through the original array to find all the ip addresses that are "/10.20.\d+.\d+/" and store them in another array (wifiArray) and store the rest in another(localArray). here's what i got so far:
var fs = require('fs');
var lineArray =
fs.readFileSync('C:/Users/intern3/zonerecords.txt').toString().split("\n");
var IP = /10.20\d+.\d+/;
var wifiArray = new Array();
var localArray = new Array();
function ArraySplit(string, Originalarray, Array1, Array2) {
var ind = 0;
for( var i=0; i < Originalarray.length; i++) {
if(String(string).match(Originalarray[i])) {
Array1[ind++] = Originalarray[i];
}
else {
Array2[ind++] = Originalarray[i];
}
}
}
ArraySplit(IP, lineArray, wifiArray, localArray);
fs.writeFile('C:/Users/intern3/test2.txt', wifiArray, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
fs.writeFile('C:/Users/intern3/test3.txt', localArray, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
fs.writeFile('C:/Users/intern3/test.txt', lineArray, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
if i run this test2.txt just prints a wall of ,,,,,,,,,,,, and test3.txt prints the original array. what am i doing wrong?
Upvotes: 2
Views: 59
Reputation: 432
Okay, found your problem. You are naming (And using!) your variables incorrectly; And you have incorrect pattern. Try var IP = /10\.20\.\d+\.\d+/;
You have:
function ArraySplit(string, Originalarray, Array1, Array2) {
// ...
// This is WRONG, as string is a PATTERN to be matched
//if(String(string).match(Originalarray[i])) {
// Now it is correct more or less
if(String(Originalarray[i]).match(string)) {
// ...
}
}
always use verbose names. It costs you nothing to have ipPatternMatcher
vs pattern
or even string
For the problem for topic, you can use reducer
const orig = [{
a: "examplea",
b: "A",
ip: "10.20.5.197"
},
{
a: "exampleb",
b: "A",
ip: "10.10.7.178"
},
{
a: "examplec",
b: "A",
ip: "10.20.75.116"
},
{
a: "exampled",
b: "A",
ip: "10.20.90.170"
}
]
var IPPattern = /^10\.20\.\d{1,3}\.\d{1,3}$/;
const accumulator = {wifiAddresses: [], localAddresses: []};
const reducer = (accumulator, value) => {
if (value.ip.match(IPPattern)) {
accumulator.wifiAddresses.push(value);
} else {
accumulator.localAddresses.push(value);
}
return accumulator;
}
console.log(orig.reduce(reducer, accumulator))
I'll try to find where you have a problem, but it seems like you have error with regexp and unescaping dot
Upvotes: 1