I want to create an empty array and then put 5 consecutive numbers in it, each one twice. And then sort them by starting from the lowest
For example: let array = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]
Asked
Active
Viewed 197 times
1

Ali Sherifov
- 25
- 5
-
Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Aug 05 '21 at 10:54
-
Alright and what have you tried so far? SO isn't a free coding service. Check out [How to Ask](https://stackoverflow.com/questions/how-to-ask) and [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) for more information – Reyno Aug 05 '21 at 10:55
-
I know how to push 5 consecutive numbers and sort them but I don't know how to put each number twice – Ali Sherifov Aug 05 '21 at 10:59
2 Answers
1
This is supposed to be fairly simple with a while
loop:
int index = -1;
int endCount = 9; //this can be any number you want
while(index <= endCount){
list.add(index++); //your list
list.add(index);
}
It's a simple while loop
concept.

Dstarred
- 321
- 2
- 10
-
-
mentioned doesn't make a difference. If it is similar you could have written in JS also instead of JAVA – DecPK Aug 05 '21 at 11:53
0
We could use Array.from()
and Array.flatMap()
to create the desired result. First we create our range of numbers, e.g. 1 -> 9 from the start and end values, then we use .flatMap() to create our duplicated numbers.
We'd wrap this up in a function getDuplicatedRange()
, with the start and end parameters:
function getDuplicatedRange(start, end) {
// Create our initial range, e.g. 1,2,3,4,5...
let range = Array.from( { length: end - start + 1}, (_,index) => index + start)
// Now duplicate each number...
return range.flatMap(n => [n,n]);
}
console.log('Range 1:', JSON.stringify(getDuplicatedRange(1,9)))
console.log('Range 2:', JSON.stringify(getDuplicatedRange(1,5)))

Terry Lennox
- 29,471
- 5
- 28
- 40