if count is 4, arr will be [ 1, 2, 3, 4 ]
if count is greater than 4, arr will be like [ 1, 2, "...", 9, 10 ]
I tried this way, but output is [ 1, 2, "..." ]
const arr = [];
const count = 10;
for (let i = 0; i < count; i++) {
if (i >= 8) {
arr.push(i + 1);
continue;
}
if (i >= 2) {
arr.push("...");
break;
}
arr.push(i + 1);
}
I'd write this as
let i=0;
for (; i < count && i < 2; i++) {
arr.push(i + 1);
}
if (count > 4) {
arr.push("…");
i = count - 2;
}
for (; i < count; i++) {
arr.push(i + 1);
}
From what I see from the OP's expected outputs/results it looks like the problem was more about creating kind of a sequence with ellipsis. In this case one could choose a much simpler approach.
Any sequence with a count lower than and equal to 4 will be created via Array.from and its optional mapFn parameter. For any count value which exceeds 4 there is no necessity of using any kind of loop; just create an array with the first two items which are always 1 and 2, followed by the ellipsis placeholder of '...', followed by the last two items which always have the values of count - 1 respectively count.
function createEllipsisSequence(count) {
let list;
if (count <= 4) {
list = Array
.from({ length: count }, (_, idx) => idx + 1);
} else {
list = [1, 2, '...', count - 1, count];
}
return list;
}
console.log('count: 3 ...',
createEllipsisSequence(3)
);
console.log('count: 4 ...',
createEllipsisSequence(4)
);
console.log('count: 5 ...',
createEllipsisSequence(5)
);
console.log('count: 6 ...',
createEllipsisSequence(6)
);
console.log('count: 10 ...',
createEllipsisSequence(10)
);
console.log('count: 11 ...',
createEllipsisSequence(11)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }