複数の文字列によるJavaScriptフィルター配列?
複数の文字列で配列をフィルタリングするには、indexOf()とともにforループを使用します。以下はコードです-
例
var details = [
'My first Name is John and last Name is Smith',
'My first Name is John and last Name is Doe',
'Student first Name is John and last Name is Taylor'
];
var isPresent;
var records = [];
var matchWords = ['John', 'Doe'];
for (var index = 0; index < details.length; index++){
isPresent = true;
for (var outer = 0; outer< matchWords.length; outer++) {
if (details[index].indexOf(matchWords[outer]) === -1) {
isPresent = false;
break;
}
}
if (isPresent){
records.push(details[index]);
}
}
console.log(records) 上記のプログラムを実行するには、次のコマンドを使用する必要があります-
node fileName.js.
ここで、私のファイル名はdemo151.jsです。
出力
これにより、次の出力が生成されます-
PS C:\Users\Amit\JavaScript-code> node demo151.js [ 'My first Name is John and last Name is Doe'
-
複数の値でJavaScript配列の要素を見つける方法は?
以下は、JavaScript配列の要素を複数の値で検索するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &nbs
-
JavaScriptでツリー化するオブジェクトのフラット配列
このようなオブジェクトの配列があるとします- const arr = [ { id: '1', name: 'name 1', parentId: null }, { id: '2', name: 'name 2', parentId: null }, { id: '2_1', name: 'name 2_1', parentId: '2' }, { id: '2_2