I have an array containing numbers from 1 to 7
const num = [1,2,3,4,5,6,7];
and two boundary values:
var first = 6
var second = 3
The desired output should be:
[6,7,1,2,3]
Explanation:
The resulting array should combine two sub-arrays:
- Numbers greater than or equal to 'first' (6) on the left side:
[6, 7]
- Numbers less than or equal to 'second' (3) on the right side:
[1, 2, 3]
I attempted to achieve this with the following code but the positions of elements are not as expected:
const result = num.filter((n,p) => {
if(p >= num.indexOf(first)) {return n}
else if(p <= num.indexOf(second)) {return n}
});
console.log(result) // [1,2,3,6,7]
An alternative method involves looping through the array twice, which is not efficient:
const num = [1,2,3,4,5,6,7];
var first = 6
var second = 3
var arr = []
num.forEach((n,p) => {
if(p >= num.indexOf(first)) {arr.push(n)}
});
num.forEach((n,p) => {
if(p <= num.indexOf(second)) {arr.push(n)}
});
console.log(arr) //[6,7,1,2,3]
Is there a better way to achieve this?