1

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!

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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(' '))

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.