i'm a newbie in javascript. Please help me to solve this problem.
How to slice an array to get only the last 2 numbers in that array - JavaScript, like this: [1234, 5432, 765764, 546542, 234, 5454] to [34, 32, 64, 42, 34, 54]
Thank you!
CodePudding user response:
You can use the map() method.
const array = [1234, 5432, 765764, 546542, 234, 5454];
const arrayMap = array.map(x => x % 100);
console.log(arrayMap);
CodePudding user response:
Well you could just use the modulus here to find the last two digits of each input number:
var input = [1234, 5432, 765764, 546542, 234, 5454];
var output = [];
for (var i=0; i < input.length; i) {
output.push(input[i] % 100);
}
console.log(output);
CodePudding user response:
Slicing in javascript would be to get a sub array of the original array, what you're looking for is a transformation of the values.
The operation you need is to take the number and apply % 100
. This will return the remainder from when dividing with 100, which becomes the last two digits.
In code this will look like:
list = [11234, 5432, 765764, 546542, 234, 5454]
newList = list.map( (num) => { return num % 100 })
console.log(newList)