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.
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.
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
var str = process.argv[2]
should do the trick –
Travel 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))
}
Another way is to use some
players = [];
const found = this.players.some(player => player === playerAddress);
if (found) {
// action
} else {
// action
}
© 2022 - 2024 — McMap. All rights reserved.