Explore the array by locating elements based on the initial two letters of each word in the array

In the given array, I am looking to find the first letters in multiple words within the same matrix. It should search through each word and return in an array if found.

For example:

const data= [ 
      "the lions of teranga",
      "tiger woods",
      "The Truman Show",
      "Shutter Island",
      "The Gold Rush",
  ]
]

If it matches "sh", it should search through each word and return:

["Shutter Island", "The Truman Show"] but not The Gold Rush

If it matches "lions", it should search through each word and return:

["the lions of teranga"]

Answer №1

This solution utilizes a combination of forEach and RegEx to extract specific words.

const data= [ 
      "the lions of teranga",
      "tiger woods",
      "The Truman Show",
      "Shutter Island",
      "The Gold Rush",
  ]
  
const filteredData = []


data.forEach(sentence => {
    let words = sentence.split(" ")
    words.forEach((word,index) => {
      if(word.match(/^lions?\w/gi)) {
        filteredData.push(sentence)
      }
    })
    
})

console.log(filteredData)

Answer №2

let items = [ 
      "ocean waves",
      "mountain peaks",
      "The Great Gatsby",
      "Forest Greens",
      "The Grand Canyon",
  ]
searchTerm = "mountain"
let results = items.filter(item => {
    text = item.toLowerCase()
    if (text.match(searchTerm.toLowerCase())){
        return item
    }
})
console.log(results)

This filter function returns all items that contain the specified search term. It is versatile and can be used to filter by any word or character.

Answer №3

//your array of elements
const elements= [ 
      "the lions of teranga",
      "tiger woods",
      "The Truman Show",
      "Shutter Island",
      "The Gold Rush",
  ];
    //your keyword for search, if constant use const instead of var
    var keyword="sh";
    //making the search case insensitive
    keyword=keyword.toLowerCase()
    //using a for loop to iterate through each element
    for(var i=0;i<elements.length;i++)
    {
       //extracting the array of words
       var wordsArray=elements[i].match(/\b(\w+)\b/g);
       
       //using another for loop to iterate through each word
       for(var j=0;j<wordsArray.length;j++)
       {
          //making the word case insensitive
          var temp=wordsArray[j].toLowerCase();
          //checking if the keyword is smaller or equal to the word's length
          if(keyword.length<=temp.length)
          {
             //checking if the first letters match
             if(temp.slice(0,keyword.length==keyword)
             {
                //first letters match, insert your logic here
             }
             else
             {
                //no match
             }
          }
          else
          {
             //keyword exceeds the word's length
          }
       }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update a specific line in a file with node.js

What is the most efficient way to replace a line in a large (2MB+) text file using node.js? Currently, I am accomplishing this by Reading the entire file into a buffer. Splitting the buffer into an array by the new line character (\n). Replacing th ...

Utilizing Vue component data within inline CSS of a Vuetify component: a step-by-step guide

I am currently working on a list component that is dynamically generated from data and I have a specific requirement to style each item based on the color provided in the data. Here is an example of the Vue component: new Vue({ el: '#app', ...

Tips for resizing images to fit the parent container dimensions

After uploading an image, I needed to adjust its dimensions. The original image was 450x700, while the parent container was 400x400. Using 'object-fit' helped fit the image to its parent container while maintaining its aspect ratio. However, I r ...

Tips for effectively handling numerous events from multiple Slickgrid instances on a single page

I'm encountering an issue with utilizing multiple Slickgrids on a single page. With the number of grids changing dynamically, I generate them within a JavaScript function and maintain them in a grid array as shown below. var columns = []; var options ...

The NgFor is unable to iterate over an array because it is being treated as an

When attempting to call a new endpoint for displaying data, I noticed that the previous set of data is wrapped with an extra pair of brackets '[]', which seems to be causing a problem. The new endpoint does not format the data in this way when I ...

The responsiveness of Slick Slider's breakpoints is malfunctioning

After implementing a slider using slick slider, I encountered an issue with the width when testing it online and in a normal HTML file. If anyone could assist me in resolving this issue, I would greatly appreciate it. Please inspect the code for both scen ...

What is the best way to create a dynamic data structure using an array?

I recently discovered that Vuejs does not track changes in data beyond the first level of an array. Is there a way to modify this behavior? new Vue({ el: '#container', data: { value: [], }, beforeMount() { this.value[0] = &apo ...

Tips for parsing data arrays in HTML templates

I have three variables and I created an array where I pushed all these three variables in. In my HTML template, I am using a table. I tried using *ngFor but it is not working, and also attempted string interpolation which also did not work. Currently, I ...

"Patience is key when waiting for an AJAX response within a jQuery loop

I've been facing difficulties in making this work using the $.Deferred object. Here is a simplified version of the code setup. g_plans = []; $(function(){ // Need to utilize a custom ajax function that returns a promise object var pageLoadPro ...

Transferring information from Node.js to HTML with the help of EJS template engine

Below is the Server Side code I am using: app.set('view engine', 'html'); app.engine('html', require('ejs').renderFile); app.use(express.static('views')); app.use(bodyParser.urlencoded({extended:true})); a ...

Encountering an error message while trying to use `npm i`

I am attempting to set up the environment in order to run tests on JavaScript. I am using Windows 10 and Python 2.7. However, when I input the command 'npm -i', I receive an error message: https://i.stack.imgur.com/j2WXE.jpg To try and resolve ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...

Leverage the values of object properties from a pair of JavaScript arrays containing objects

I am working with two arrays let arr1 = [{'id': 'ee', 'seat': '12'}, {'id': 'aa', 'seat': '8'} ] let arr2 = [ {'id': 's22', 'num': '&ap ...

"Owlcarousel Slider: A beautiful way to showcase

Currently, I am working on a project that involves implementing a slider. Since I lack expertise in JavaScript, I opted to use a plugin called owlcarousel. The challenge I'm encountering relates to the sizing of the container for the items. I'm ...

What is the syntax for populating an attribute on the same line as v-for in Vue.js?

I am currently working on a simple loop utilizing Vue to iterate over an array of objects and populate table rows. <tr v-for="user in users"> <td>{user.name}</td> <td>{user.id}</td> </tr> However, I also need to as ...

Error: string literal left incomplete with spaces only

I am attempting to run parameters from a JavaScript function, but I am encountering an issue with quotes when there is a white space present. This error specifically pertains to Mozilla: SyntaxError: unterminated string literal Below is the relevant p ...

The dropdown menu is extending outside the header in a right-to-left (RTL) direction

I have implemented the jQuery code below to prevent the dropdown from extending beyond the header area. It works perfectly in the normal LTR version. However, I need a solution for the RTL version. How can I achieve this? jQuery $('.primary-menu .dr ...

Error encountered during react parsing: An unexpected '#' error was encountered when using the react-router-sitemap npm package

I'm currently working on building a sitemap using the react-router-sitemap npm package. After installing all the necessary dependencies related to react-router-sitemap, I created a file called sitemap-generator.js and added the following code. router ...

I'm noticing multiple repeated entries appearing when I try to set the cookie - what could be causing

Currently, I am utilizing the library js-cookie instead of my previous use of jquery.cookie. I have encountered an issue related to duplicating cookie entries. There are occasions when I invoke the following method: Cookies.set('my-cookie-name', ...

Refresh the table dynamically in Django without the need to reload the entire page

Seeking assistance to update a small table with new data every 10 seconds on a Django website. The data is parsed into JSON and refreshed in the database, then displayed on the front-end. Looking for help with writing AJAX code to continuously refresh the ...