Sort the collection of words by their corresponding suffixes

Looking to use JavaScript to compare two lists and extract words from WORDLIST that end with the characters in END (not in the middle of the word). I am also open to using jQuery for this task.

var WORDLIST = ['instagrampost', 'facebookpost', 'google']
var END = ['post', 'gle']

function compare() {
    var final = WORDLIST.endsWith(END, END.length);
    console.log(final);
}

// To do: count signs at end
// Extract words from end of WORDLIST based on length of END
// Save any matching words from WORDLIST as results

Answer №1

To filter your list of words, called WORDLIST, based on whether any item in the array END is a valid ending for a word, you can use the Array.prototype.some() method along with the String.prototype.endsWith() function:

const WORDLIST = ['instagrampost', 'facebookposting', 'google'],
      END = ['post', 'gle'],

      result = WORDLIST.filter(word =>
        END.some(end => word.endsWith(end)))
        
console.log(result)

Note: For case-insensitive matching, you can convert both the word and the ending to lowercase before using endsWith() like this:

word.toLowerCase().endsWith(end.toLowerCase())

Answer №2

Here's a non-regex solution that uses the indexOf method:

var WORDLIST = ['instagrampost', 'facele', 'facebookpost', 'google', 'dnuiwa']
var END = ['post', 'gle']

function endsWith(wordlist, end){
  return wordlist.filter((w) =>
    end.filter((e) => w.indexOf(e) == w.length - e.length).length > 0
  );
}

console.log(endsWith(WORDLIST, END))
  

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

Troubles with configuring the Express server in relation to the public directory

After creating two separate bundles for my server and client, I encountered an issue where the client bundle is not being downloaded by the browser when accessing the root route. To address this, I instructed Express to treat the public/ folder as a freel ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

Enhancing the camera functionality of the HTML <input> tag for iPhone and Android devices

I am currently working on a mobile web application that requires access to the device's camera. I am aware that this can be achieved using the following code: <input type="file" accept="image/*" capture="camera" /> The code snippet above suc ...

Seeking guidance on capturing the correct error message when using JSON stringify?

Imagine I have an object structured as follows var obj = { "name": "arun" age } After attempting JSON.stringify(obj), it results in an error due to the improper structure of the obj. I am interested in capturing this error displayed in the console and pr ...

One way to filter using a single array

Currently testing some angularJS with this particular example http://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_filter <ul> <li ng-repeat="x in names | filter : 'i'"> {{ x }} </li> </ul> Is ther ...

Creating texture using an array in three.js

I've been experimenting with generating textures from arrays in threeJS but I'm encountering unexpected results. It seems like the method I'm using to generate the texture is incorrect. When I use the texture from the following link, every ...

Tips for effectively showcasing the counter outcome amidst the increase and decrease buttons

Currently, I am in the process of learning Angular and have created a component called quantity-component. Within the quantity-component.component.html file, I have implemented 2 buttons for increment (denoted by +) and decrement (denoted by -). The decrem ...

I'd like to know how to retrieve the start and end dates of a specific month using JavaScript

How can I retrieve the start and end date of the current month? const currentDate = new Date(); const startOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); const endOfMonth = new Date(currentDate.getFullYear(), currentD ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

Obtaining the Value of Input Text

Let's say you have the following HTML code: <form> Enter hash here: <input type="text" name="hash"> <button type="submit" formaction="/tasks/">Retrieve Url</button> </form> Is there a way ...

Deployment to Amazon Amplify encounters failure when using Next JS

I've been encountering continuous failures while trying to deploy an SSG app on Next JS. The build consistently fails, and I'm met with an error message. Despite following the deployment documentation for SSG sites on Amazon diligently, the error ...

Is it possible to display a React stack trace in the browser using a custom component?

I am currently brainstorming a solution to display a React stack trace error message in the browser with the same formatting and layout as it appears in the terminal. For example, here is the stack trace error displayed in the terminal, and I aim to replic ...

Error message: "Property undefined when Angular attempts to call a function from jQuery/JavaScript."

I'm currently attempting to invoke an angular controller from my JavaScript code. This is my first encounter with Angular and I must admit, I'm feeling a bit overwhelmed! I've been following this example: Unfortunately, when testing it out ...

a JavaScript file containing only a require statement with a list of dependencies and a function

I have a question regarding the implementation of the "require" statement in JavaScript. I am just starting to work with JS and Dojo, and I encountered an issue while developing a Plug-in for a website. The main Java class of the plugin makes a reference t ...

Is there a way to activate the jquery event handler only when certain events occur in a particular sequence?

Currently, I am facing a particular scenario involving the use of Bootstrap tabs in combination with MarionetteJS. I want to ensure that when a tab is clicked, my designated handler function is only called after the 'show.bs.tab' event for that s ...

"Scotchy McScotchface's to-do list application powered

How is the index.html (frontend Angular) being triggered? The tutorial mentioned that by including one of the following routes in route.js, the frontend gets called app.get('*', function(req, res) { res.sendfile('./public/index.html&ap ...

Looking to activate a button upon clicking a button on a different page using php and javascript

Is it possible for the first user logged in on one page to have a button, and when clicked, enable a disabled button on another page where the second user is logged in? This functionality needs to be implemented using PHP/JavaScript. Thank you in advance ...

Creating a dynamic multi-item carousel with Materialize (CSS) cards using data from a loop - here's how!

Using a for loop, the following code generates a list of cards. These cards are intended to be displayed in a carousel with 4 cards visible at once, and a next arrow button allows users to navigate through the next set of 4 cards. Materialize cards have ...

Using Perl arrays within a PostgreSQL INSERT query

There seems to be a logical issue within my code. In my MongoDB database, I have fields for template, value, row, and column. For example, if $record->{template} is T1, $record->{column} is 1, and $record->{row} contains dates in the format "d.m.Y ...

"Troubleshooting Error: When accessing a property in AngularJS,

My goal is to retrieve a date value. However, I encounter an error message saying 'Cannot read property 'NTLI' of undefined' whenever the checkbox is unchecked and the date picker is invisible. Strangely enough, everything works fine wh ...