1

I'm beginner and have one question.

I have one um array and need show just 2 in 2 elements of array elements, my code is:

var datas = [];

followTotalsData.forEach(function(dataByDay) {
    datas.push(dataByDay[1]);
});


datas = [1, 2 , 3 , 4, 5, 6, 7, 8, 9, 10];

But I need the array formated as

var newDatas = [2, 4, 6, 8, 10];
1
  • test if each items of your array are even numbers, if not delete them Commented Jul 9, 2015 at 14:48

3 Answers 3

3

I'm interpreting your question as

How can I only get Numbers that are multiples of 2 from my Array of Numbers

Use the remainder operator %.
If x % y is 0 then y divides x.

var datas = [1, 2 , 3 , 4, 5, 6, 7, 8, 9, 10];

var newDatas = datas.filter(function (e) {return e % 2 === 0;});
// [2, 4, 6, 8, 10]
Sign up to request clarification or add additional context in comments.

Comments

0

Another solution:

var followTotalsData = [1, 2, 3, 4]; 
var result=[];

followTotalsData.forEach(function(data) {
    if (data % 2 == 0 ) result.push(data);
});
console.log(result);

Comments

0

If you want every other element of the array, use the modulus function on the index of the array:

var datas = [1, 2 , 3 , 4, 5, 6, 7, 8, 9, 10];

var newDatas = datas.filter(function (e, index) {return index % 2 === 1;});
// [2, 4, 6, 8, 10]

var newDatas = datas.filter(function (e, index) {return index % 2 === 0;});
// [1, 3, 5, 7, 9]

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.