Home > OS >  Filter an array of strings that have only ONE word
Filter an array of strings that have only ONE word

Time:10-05

I'm working on a simple dictionary website challenge for a job position, and I need to consume a JSON file with an array of strings and display a list of words on the screen; however, this file provided by the challenge has not only words but phrases as well, which is also being displayed on the screen, and I would like to get rid of them!

I'm trying to filter the array and get the strings with only ONE word.

Is that possible? If so, could you please help me?

See below a part of the array. This file has more than 130k strings with words/phrases, so I can't delete the phases myself!

[
  "acciaccatura",
  "accident",
  "accidental",
  "accidentally",
  "accidentally on purpose",
  "accident and emergency",
]

Also, see below the code with the .map() I'm using to display the words on the screen.

 <div className="word-container">
   {words.map((data) => (
     <span className="word">{data}</span>
   ))}
 </div>

Many thanks!

Ps.: this is my first ever question here, so I apologise if I made any mistake. I'm also new to coding, so I'm trying to get used to using more StackOverflow!

CodePudding user response:

That should do what you ask:

 <div className="word-container">
   {words.filter(w => w.indexOf(' ') < 0).map((word) => (
     <span className="word">{word}</span>
   ))}
 </div>

The filter leverages on the indexOf method, which finds the first index of a string occourrence, that is a space in your case.

Negative index means no space found, hence just a single word.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

CodePudding user response:

You can add a condition to check whether there is any space within the array value or not, using the Array.prototype.includes

The below code will render all the words from your array that has no spaces.

<div className="word-container">
   {words.map((data) => (
     !data.includes(" ") && <span className="word">{data}</span>
   ))}
 </div>

The another approach could be using the Array.prototype.filter and filter out all the values that contains space using includes array method. The below code will return you a new array and you can use that directly in your map function.

words.filter(data => !data.includes(' '))

CodePudding user response:

You can look for spaces to determine if the element in the array is a phrase or word. If index of the element is equal to -1 it means that it doesn't have any spaces, so is a word.

<div className="word-container">
   {words.filter(item => item.indexOf(' ') == -1).map((word) => (
     <span className="word">{word}</span>
   ))}
 </div>
  • Related