Home > Blockchain >  React Js - create new array with the last two letters in string from previous array
React Js - create new array with the last two letters in string from previous array

Time:01-08

I would like to loop through and array and then get the last two letters from each string and create a new array with them?

my current array is

myArray = [Qe3,Ke4,Qe5,Je6]

I would like to end up with this

newArray = [e3,e4,e5,e6]

this is for www.chessonline.app

CodePudding user response:

you need to loop over the array and cut first character !

 const myArray = ['Qe3','Ke4','Qe5','Je6']
 const newArr = myArray.map((el) => el.substring(1));
 

CodePudding user response:

Use slice


const newArray = myArray.map(str => str.slice(-2)); // Use map() to apply a function to each element of the array
// The function uses slice() to return the last two characters of each string

console.log(newArray); // ['e3', 'e4', 'e5', 'e6']


CodePudding user response:

We can use a slice here:

var myArray = ["Qe3", "Ke4", "Qe5", "Je6"];
var output = myArray.map(x => x.slice(-2));
console.log(output);

  • Related