文字列一致のために、アレイ内を検索

スニルミーナ:

どのような私が持っています

var sentence = 'My country is India';
var array = ['Intel,' 'Goa', 'Green Day', 'India', 'Ice', 'India'];

私は必要な結果

  index = array.indexOf(sentence); // it should return 3

そして、これは私はそれが動作しようとしたものですが、ビッグデータを使用するときには非常に遅く、フリーズし、停止作業します

words = sentence.split(' ');
var i;
for (i = 0; i < words.length; i++) {
    w = words[i];
    a = array.indexOf(w);
    console.log(a);
}

アップデート:私は、ソリューションの下にしようとしたが、それでもその実行が継続的にいくつかは、1 speeak文アレイトリガーが何度も何度も私はこれがあると思うので、だから私は音声にGoogleの音声に取り組んでいます動作を停止する理由をいくつかの時点後の凍結

アップデート2:上記の例では、私は、単一の単語、すなわち「インド」が、何を検索した場合、私にその複数の単語のように「ニール・アームストロング」その後、スプリット方式のようなその人の名は作業しません。

CertainPerformance:

Array#indexOfあるO(n)操作-インタプリタは、一致かどうかがありますかどうかを確認するために、アレイ全体を通じて最悪の場合を反復しなければなりません。ループ中で行われた場合、この増大する計算複雑O(n ^ 2)遅くなり、。

あなたは代わりにセットを使用することができます- Set#hasの複雑さがあるO(1)(に全体的な複雑さを軽減しますO(n))

var sentence = 'My country is India';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = new Set(sentence.split(' '));
console.log(
  array.findIndex(word => words.has(word))
);

またはオブジェクト(オブジェクトキールックアップがありO(1)すぎて):

var sentence = 'My country is India';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = Object.fromEntries(
  sentence.split(' ').map(key => [key])
);
console.log(
  array.findIndex(word => words.hasOwnProperty(word))
);

あなたもどのように使用できるかを参照してくださいfindIndexコードはるかに簡潔を作ること。

あなたは試合に期待しているアイテムは、二つの単語で構成されている場合、また、隣同士に2つのワードのすべての発生を一致させます:

var sentence = 'My country is Green Day';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const words = new Set(sentence.split(' '));
const pattern = /(?=(\S+ \S+))/g;
while (true) {
  const match = pattern.exec(sentence);
  if (!match) {
    break;
  }
  words.add(match[1]);
  pattern.lastIndex++;
}
console.log(
  array.findIndex(word => words.has(word))
);

より一般的なソリューションについては、Setに追加する文の単語の上に、それぞれの番号のために、その後、あなたが収集する必要のある単語の数を識別するために反復を入力配列を確認することができます。

var sentence = 'My country is Green Day';
var array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice'];

const combinationsNeeded = new Set();
for (const substr of array) {
  combinationsNeeded.add(substr.split(' ').length);
}
const wordsSet = new Set();
const sentenceWords = sentence.split(' ');
for (const comb of combinationsNeeded) {
  let endIndex = comb;
  for (let i = 0; i + comb <= sentenceWords.length; i++) {
    // uncomment the below to see all the words wordsSet gets
    // console.log(sentenceWords.slice(i, i + comb).join(' '));
    wordsSet.add(sentenceWords.slice(i, i + comb).join(' '));
  }
}

console.log(
  array.findIndex(substr => wordsSet.has(substr))
);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=17248&siteId=1