igodie igodie -4 years ago 131
Node.js Question

Filter one Array which is in another array

So I have one array which contains two different arrays:

var _staticRoutingTable = [];

function StaticRoute(directory, extentions) {
this.dir = directory;
this.extentions = extentions;
}

_staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"]));
_staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"]));


Lets say I want only get the "dir" Array where the name of the folder is "somefolder".

So I dont want smth like this because...:

return _staticRoutingTable.forEach(function callb(route) {
return route.dir.filter(function callb(directory) {directory=="somefolder" })
});


.... I get dir + extention array. How can I only filter one array (in this case "dir").

Answer Source

I'm stil not sure if I understand your question correctly - but to get an array like ['something'], you can use find:

var _staticRoutingTable = [];

function StaticRoute(directory, extentions) {
    this.dir = directory;
    this.extentions = extentions;
}

_staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"]));
_staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"]));

let foo = _staticRoutingTable.find(function (a) {
    return a.dir.indexOf("somefolder") > -1;
});
if (foo) {
    console.log(foo.dir);    
}

Note that this will return the first match only. If there are multiple possible matches you're interested in, you can switch filter for find and work with the resulting array then.

However, as you are searching for 'somefolder' and want to return an array like ['somefolder'], it would be easier to just do

console.log(['somefolder']);

...

This works for multiple matches:

    var _staticRoutingTable = [];

    function StaticRoute(directory, extentions) {
        this.dir = directory;
        this.extentions = extentions;
    }

    _staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"]));
    _staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"]));

    let foo = _staticRoutingTable.filter(function (a) {
        return a.dir.indexOf("somefolder") > -1;
    });
    foo.forEach(function (v) { console.log(v.dir); });

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download