简体   繁体   中英

How to slice an array to get only the last 2 numbers in that array - JavaScript

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!

You can use the map() method.

 const array = [1234, 5432, 765764, 546542, 234, 5454]; const arrayMap = array.map(x => x % 100); console.log(arrayMap);

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);

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM