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.
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);
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" }
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' }
// ]