For this, you can use for loop along with if condition. Let’s say the following is our array −
var numbers = [1, 2, 34, 56, 78, 90, 100, 110, 40, 70, 67, 77, 34, 68, 89, 91, 94];
We have set a counter to set a value. This value is set to display a fixed number of values −
var counter = 6;
The above shows the result will be 6 values.
Example
Following is the code −
var numbers = [1, 2, 34, 56, 78, 90, 100, 110, 40, 70, 67, 77, 34, 68, 89, 91, 94];
var counter = 6;
var newNumbers = [];
var start = 0;
for (var index = 0; index < numbers.length; index++) {
if (index % 2 != 0) {
start++;
if (start <= counter) {
newNumbers.push(numbers[index]);
}
}
}
console.log(newNumbers);To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo231.js
Output
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo231.js [ 2, 56, 90, 110, 70, 77 ]