JS Finding all individuals sharing a common last name

I recently started coding and came across this problem that I'm struggling to solve.

The task at hand is to create a function that takes an array of full names and returns only those with the last name "Smith".

  Example: ['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones'] => ['Rebecca Smith', 'Harry Smith']

Here's the code I've written so far:

function getSmiths(arr) {
  return arr.filter(a =>a.includes("Smith"))
 }
 
 console.log(getSmiths(['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones']));

I've tested my code with the following cases:

describe("getSmiths", () => {
  it("returns [] when passed []", () => {
    expect(getSmiths([])).to.eql([]);
  });
 it("returns a Smith from a mixed arrau", () => {
    expect(getSmiths(["Harry Smith", "Charlotte Bank"])).to.eql([
      "Harry Smith"
    ]);
  });
  it("returns multiple Smiths from a mixed array", () => {
    expect(getSmiths(["Harry Smith", "Charlotte Bank"])).to.eql([
      "Harry Smith"
    ]);
  });
  it("ignores Smiths found in first names", () => {
     expect(getSmiths(["Smithy Jones", "Harry     Smith"])).to.eql(["Harry Smith"]);
  });
  it("ignores Smiths found in extended last names", () => {
     expect(getSmiths(["John Smith", "Chris Smithy"])).to.eql(["John     Smith"]);
  });
});

Can anyone offer any insights as to why my code isn't working? Any suggestions would be greatly appreciated!

Answer №1

When utilizing the include function, it will search for the specific keyword within the entire string.

  1. Utilizing the endsWith method:

let arr = ['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones'];

    let result = arr.filter(element => element.endsWith('Smith'));

    console.log(result);

  1. Using regex to filter results:

let arr = ['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones'];

let result = arr.filter(element => /\ssmith$/ig.test(element));

console.log(result);

Answer №2

Have you identified which specific tests in the test group are showing failures?

The function you have created to extract array members containing the string 'Smith' will capture any items with 'Smith' anywhere in them and return the entire string.

In the 4th test within the group, both array items will be retrieved as they are stored (e.g., the second item will display as "Harry Smith").

Similarly, in your final test, both items will be returned, with the first one being presented as "John Smith".

To rectify this issue, modify your filter test to focus specifically on the last name by potentially splitting each string and evaluating against the last name only. You may need to figure out how best to implement this approach.

It appears that the last test is likely to fail based on the way it has been written. It seems like the intention was for it to return "John Smith" while ensuring that "Smithy" fails the test. Consider refining your filter criteria to match the last name EXACTLY to "Smith" rather than just including it.

Best of luck!

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

How can a form be submitted in Extjs without using ajax?

Hello there! I'm attempting to submit an extjs form without using ajax and display the result on the next page. Below is my code: Ext.define('test.from', { extend: 'Ext.form.Panel', alias: 'widget.test.form', ...

Launching a web application directly from a USB drive

Exploring the world of Javascript frameworks and nodejs, I recently encountered a unique requirement that got me thinking about their practical application. The requirements are as follows: --I need to create a lightweight website that can be run from a U ...

JavaScript / AngularJS - Efficient Boolean Switching

My group of Boolean variables can toggle other variables to false when set to true. I am looking for a clean pattern for this approach, especially since the number of boolean variables may increase. angular.module("app", []) .controller("controller", ...

Stand-alone Login Page for Angular 2/4

I've put together a website using the MEAN stack, and here's how my structure looks: root app auth auth.routes.ts auth.service.ts app.component.html app.component.ts app.routing.ts In my app.routung.ts, you'll find this code snippe ...

The caching functionality in the React server component is failing to store the results effectively

My issue involves a simple function that retrieves data asynchronously. Despite using the cache wrapper to prevent multiple calls, the function is being executed multiple times when the page loads. How do I ensure that the cache functionality works as ex ...

Create a form in a PHP file containing a pair of buttons for selecting a specific action

Consider the following HTML code snippet: <body onload="showcontent()"> <!-- onload attribute is optional --> <div id="content"><img src="loading.gif"></div> <!-- exclude img tag if not using onload --> < ...

How can I confirm that AJAX is functioning correctly on my website?

Today marks the first time I am delving into the realm of AJAX. Utilizing AJAX from the servers at Google, here is the code I have implemented: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> I've ...

Unique validation feature implemented in Parsley.js runs through validation loop twice

I've spent the entire afternoon trying to figure this out, but I just can't seem to debug it. The issue arises when I do a hard refresh of the page and my custom async validator runs twice, yet only sends one request to the server. window.Parsle ...

Spacing issues while utilizing the <textarea> element

<tr> <td> <b>Escalation: </td></b> <td> <TextArea name='escalation' onKeyDown=\"limitText(this.form.escalation,this.form.countdown,100);\" onKeyUp=\"limitText ...

Choose the highest three elements in JSON arrays

The data source shows the preferences of users towards different video categories. user_id video_interest 1 [{"category":"a","score":1},{"category":"b","score":2},{"category":"c&quo ...

An Iframe lacks the ability to showcase HTML content, unlike a browser which is capable of doing

I'm struggling to get my Iframe to show the html string properly. Here's the content of the string: var='<BODY style="MARGIN: 0px" bgColor=#ffffff marginwidth="0" marginheight="0"> <SCRIPT language=JavaScript> var Caller_User_Ty ...

React failing to detect updated state from input fields during initial rendering

Hey there, fellow developers! I'm currently working on a simple client in React to test out some functionalities of my API. While my Node.js knowledge is extensive, my understanding of React, states, and hooks is still a work in progress. The Issue: ...

The proper way to apply the margin-top property in javascript using the DOM style

Struggling to get my div element perfectly centered on the screen. It's aligned in the center, but the top margin stubbornly refuses to budge from the top. I attempted setting divElement.style.marginTop = "100px";, yet saw no change in position. //t ...

unable to extract category information from the table property by referencing a foreign key

When I click on a property from the list, I am able to retrieve the detail property per id. However, I have successfully obtained the property value but am struggling to fetch the category values using the foreign key. Below is my component test.jsx: impo ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

Mixing controllers with the same name in AngularJS from different modules can lead to

Recently, while working on an AngularJS web application with multiple sub-modules, I encountered a situation where two sub-modules had controllers with the same name due to them both having CRUD functionality. Here's a snippet of the code structure: ...

Is it necessary to utilize body-parser in our code?

In my research, I've noticed that many tutorials recommend using both express.json and bodyParser.json middleware. But aren't they essentially performing the same function? ...

The array cannot be accessed outside of the block

I have a method that generates an array called 'venues'. However, every time I attempt to access this array in a different method, it shows as 'null'. Here is the method: - (void)startSearchWithString:(NSString *)string { [self.las ...

Managing clicks outside a specified Component using React Higher Order Components

I have a desire to create a Higher Order Component that can manage clicks outside a specified component. This component will trigger a specific function when a user clicks outside the defined boundaries. The HOC requires two parameters: BoundaryComponent ...

Angular 2: Dynamically Adjusting View Components Based on URL Path

Apologies for the unconventional title. I struggled to come up with a better one. My goal is to develop an application with a simple 3-part structure (header / content / footer). The header should change based on the active route, where each header is a s ...