1

Example:

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"]

I want to print the last element of each string, so:

output: is, Name, is, my

I have no idea where I should start. My first thought was to split the array and print the last index, but I didn't succeed

Bassam
  • 497
  • 4
  • 12

3 Answers3

2

Use Array.map

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"];
let result = someArray.map(v => {
  let temp = v.split(" ");
  return temp[temp.length-1];
})
console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
2

You can use a regular expression to match the last word.

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"]
var result = someArray.map(item => item.match(/\w+$/)[0]);
console.log(result);
sasensi
  • 4,610
  • 10
  • 35
1
var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"];
var lastElements = "";

someArray.forEach(str => {
  splitStr = str.split(" ");
  lastElements += splitStr[splitStr.length - 1] + ", ";
});

console.log('output: ', lastElements);

//Outputs output:  is, Name, is, my, 
Sam Walpole
  • 1,116
  • 11
  • 26