Eyal Cohen
Eyal Cohen

Reputation: 1288

what is the best way to find string inside array in node.js?

I have a node.js script where I want to find if a given string is included inside an array. how can I do this?

Thanks.

Upvotes: 7

Views: 41335

Answers (3)

Dennis Gonzales
Dennis Gonzales

Reputation: 111

Another way is to use some

players = [];

const found = this.players.some(player => player === playerAddress);

if (found) {
    // action
} else {
    // action
}

Upvotes: 2

xShirase
xShirase

Reputation: 12399

If I understand correctly, you're looking for a string within an array.

One simple way to do this is to use the indexOf() function, which gives you the index a string is found at, or returns -1 when it can't find the string.

Example:

var arr = ['example','foo','bar'];
var str = 'foo';
arr.indexOf(str); //returns 1, because arr[1] == 'foo'

str = 'whatever';
arr.indexOf(str); // returns -1 

Edit 19/10/2017

The introduction of ES6 gives us : arr.includes('str') //true/false

Upvotes: 33

chriskelly
chriskelly

Reputation: 7736

In NodeJS, if you are looking to match a partial string in an array of strings you could try this approach:

const strings = ['dogcat', 'catfish']
const matchOn = 'dog'

let matches = strings.filter(s => s.includes(matchOn))

console.log(matches) // ['dogcat']

EDIT: By request how to use in context fiddle provided:

var fs = require('fs');                                           
var location = process.cwd();                                     


var files = getFiles('c:/Program Files/nodejs');                                 
var matches = searchStringInArray('c:/Program Files/nodejs/node_modules/npm/bin', files);


console.log(matches);                                             

function getFiles (dir, files_){                                  
    var str = process.argv[2];                                    
    files_ = files_ || [];                                        
    var files = fs.readdirSync(dir);                              
    for (var i in files){                                         
        var name = dir + '/' + files[i];                          
        if (fs.statSync(name).isDirectory()){                     
            getFiles(name, files_);                               
        } else {                                                  
            files_.push(name);                                    
        }                                                         
    }                                                             

    return files_;                                                
}                                                                 

function searchStringInArray (find, files_) {                     
    return files_.filter(s => s.includes(find))                   

}                                                                 

Upvotes: 5

Related Questions