I have the following array (testArray) and i wish to extract all the states to string ('Arizona','Alaska','Florida','Hawaii','Gujarat','Goa','Punjab'...). Are there any simpler ways to do that?
let testArray: State[];
testArray = this.getStates();
getStates() {
return [
new State(1, 1, 'Arizona'),
new State(2, 1, 'Alaska'),
new State(3, 1, 'Florida'),
new State(4, 1, 'Hawaii'),
new State(5, 2, 'Gujarat'),
new State(6, 2, 'Goa'),
new State(7, 2, 'Punjab'),
new State(8, 3, 'Queensland'),
new State(9, 3, 'South Australia'),
new State(10, 3, 'Tasmania'),
new State(11, 4, 'Penang')
];
}
The simplest way is as follows
getStates().map(x=>x.StateName).join(",")
Example is given below
function State(id,val,StateName) {
this.id = id;
this.val = val;
this.StateName = StateName;
}
function getStates() {
return [
new State(1, 1, 'Arizona'),
new State(2, 1, 'Alaska'),
new State(3, 1, 'Florida'),
new State(4, 1, 'Hawaii'),
new State(5, 2, 'Gujarat'),
new State(6, 2, 'Goa'),
new State(7, 2, 'Punjab'),
new State(8, 3, 'Queensland'),
new State(9, 3, 'South Australia'),
new State(10, 3, 'Tasmania'),
new State(11, 4, 'Penang')
];
}
//Simplest Way is as follows
console.log(getStates().map(x=>x.StateName).join(","))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With