0

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!

3 Answers 3

2

You can use the map() method.

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.