'function to Get array and specific start letter and end letter and then return a list of names that starts and end with them

I have a long array of objects. I want to write a function to find for example names that start with specific letter and end with another specific letter and return a list of names that starts and end with them.

I tried some solutions but did not get answer.

Here I use a simple list: and I want a list that name start with "A" and end with "i" or any other case

myList = [{name: "Aji",family: "Ziansi"}, { name: "Alex", family: "ortega"}, {name:"Amandi",family: "Sedirini"}];

Output should be like this:

desiredLiset = [{name: "Aji",family: "Ziansi"}, {name:"Amandi",family: "Sedirini"}];

just in function declaration method.

Any solutions would be appreciated.



Solution 1:[1]

We can use Array.filter()

const myList = [{
  name: "Aji",
  family: "Ziansi"
}, {
  name: "Alex",
  family: "ortega"
}, {
  name: "Amandi",
  family: "Sedirini"
}];

const filterList = (list, start, end) => {
  return list.filter(obj => {
    const name = obj.name;
    return name[0] === start && name[name.length - 1] === end;
  });
};

const filtered = filterList(myList, "A", "i");
console.log(filtered);

Solution 2:[2]

You can use .filter() to get a list of the names you want:

myList = [{name: "Aji",family: "Ziansi"}, { name: "Alex", family: "ortega"}, {name:"Amandi",family: "Sedirini"}];

let desiredLiset = myList.filter(function(n){
    return n.name.match(/^A.*i$/i) // Names that begin with 'A' and end with 'i'
});

console.log(desiredLiset)
// 0: Object { name: "Aji", family: "Ziansi" }
// ?1: Object { name: "Amandi", family: "Sedirini" }

Solution 3:[3]

Try this:

myList = [{name: "Aji",family: "Ziansi"}, { name: "Alex", family: "ortega"}, {name:"Amandi",family: "Sedirini"}];

const start='A'
const end='i'
const startEndRE = new RegExp(`^${start}.*${end}$`)
myList.filter(item=>(
    startEndRE.test(item.name)
))

// Result 
// [
//   { name: 'Aji', family: 'Ziansi' },
//   { name: 'Amandi', family: 'Sedirini' }
// ]

Solution 4:[4]

It is also possible to do using endsWith() and startsWith()

try:

const myList = [{ name: "Aji", family: "Ziansi" }, { name: "Alex", family: "ortega" }, { name: "Amandi", family: "Sedirini" }];

const newlist = myList.filter((obj) => obj.name.startsWith('A') && obj.name.endsWith('i'));

console.log(newlist);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kmoser
Solution 3 SteveGreenley
Solution 4 Fernando Cavalcanti