I'm new to coding and have been given this question, but I'm unsure to why my code doesn't work.
This is the question I have been given;
Create a function that takes an array of full names and returns an array containing only the people whose last name is Smith.
E.g. ['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones'] => ['Rebecca Smith', 'Harry Smith']
This is the code that I have written;
function getSmiths(arr) {
return arr.filter(a =>a.includes("Smith"))
}
console.log(getSmiths(['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones']));
my code is being run against this test;
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"]);
});
});
Dose anyone have any suggestion to why my code doesn't work?
Well you're using include which will search for smith in the complete string.
endsWith
let arr = ['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones'];
let op = arr.filter(e=> e.endsWith('Smith'))
console.log(op);
let arr = ['Charlotte Jones', 'Rebecca Smith', 'Harry Smith', 'John Smithy', 'Smith Jones'];
let op = arr.filter(e=> /\ssmith$/ig.test(e))
console.log(op);