Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

javascript - How do I match string with the array of strings

I have an Array of strings as:

todo=[

'Get up',
'Brush my teeth',
'Go to work',
'play Games'
];

I am trying to match it with this:

Template:

<input (input)="checkArrays($event)" />

while in my Component.ts the function I am using for it is :

checkArrays(e){
let query=e.target.value;
console.log(query);

let todoResult = this.todo.findIndex((item) => { return item.startsWith(query);})
let doneResult = this.done.findIndex((item) => { return item.startsWith(query);})
if(doneResult!=-1){
  console.log('found in Tasks (done)'+doneResult)
}if(todoResult!=-1){
  console.log('found in Tasks (todo)'+todoResult)
}

what this does is that when i start typing 'G' it matches the very first item in the array which is 'Get up' and do not match with 'Go to work'. It matches with 'Go to work' when i type 'Go'. The functionality I want is basically it should give me both the 'Get up' and 'Go to work' when I start typing 'G'. some sort of the sub-string like functionality.

question from:https://stackoverflow.com/questions/65879597/how-do-i-match-string-with-the-array-of-strings

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use filter() instead of findIndex(). So it can be:

checkArrays(e) {
  const query = e.target.value;
  
  const todoResult = this.todo.filter(item => item.startsWith(query));
  const doneResult = this.done.filter(item => item.startsWith(query));
  
  if (doneResult.length > 0) {
    console.log(`found in Tasks (done) ${doneResult}`)
  }
  if (todoResult.length > 0) {
    console.log(`found in Tasks (todo) ${todoResult}`)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...