Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Convert Array into string

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')
 ];
}
like image 762
scholarwithfire Avatar asked Dec 06 '22 10:12

scholarwithfire


1 Answers

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(","))
like image 163
Sourabh Somani Avatar answered Dec 24 '22 19:12

Sourabh Somani