Searching in array for numbers between two numbers

Joined
Oct 2, 2022
Messages
1
Reaction score
0
How can i extract from this array a new array in which the numbers between 5 and 6 are written

For example

let arr = [2,4,3,5,4,2,3,4,2,5,6];

I want to extract in new array this numbers 4,2,3,4,2,5
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
Alright.
if you know the key value, in your case 4 to 10 you can go like this
Code:
function array_between(a,b,c){
var backs=new Array();
for(var i=(a+1); i<b; i++){
backs.push(c[i]);
}
return backs;
}

console.log(array_between(3,10,arr));

If you don't know the key values, it's more tricky as you don't have unique element values.
But it should be something like this.

Code:
function findBetweenValues(a,b,c){
     var found=0;
     var s=false;  var e=false;
    var backarrays=new Array();
      for(var i=0; i<c.length; i++){
              if(c[i]==a && found<1){s=i; found=1; }else if(c[i]==b && found==1){e=i; found=0; backarrays.push(array_between(s,e,c)); }
                     
              }
      
return backarrays;

}
console.log(findBetweenValues(5,6,arr));

should return arrays (in that case just one) [4,2,3,4,2,5]

So all in all
Code:
function array_between(a,b,c){
var backs=new Array();
for(var i=(a+1); i<b; i++){
backs.push(c[i]);
}
return backs;
}
function findBetweenValues(a,b,c){
     var found=0;
     var s=false;  var e=false;
    var backarrays=new Array();
      for(var i=0; i<c.length; i++){
              if(c[i]==a && found<1){s=i; found=1; }else if(c[i]==b && found==1){e=i; found=0; backarrays.push(array_between(s,e,c)); }
                     
              }
      
return backarrays;

}
let arr = [2,4,3,5,4,2,3,4,2,5,6];
console.clear();

console.log('ARROUT');
console.log(array_between(3,10,arr));
console.log('ARROUTB');
console.log(findBetweenValues(5,6,arr));

 
Last edited:
Joined
Nov 13, 2020
Messages
302
Reaction score
38
Doing it in 3 steps
Code:
<!DOCTYPE html>
<html>
<head>
<title>Extract an Array from an Array</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>
<p id="demo"></p>
<script>
var myArray = [2,4,3,5,4,2,3, 4, 2, 5, 6,3,7,9];
myArray.splice(0, myArray.indexOf(5)+1);
myArray.splice(myArray.indexOf(6));
document.getElementById('demo').innerHTML = myArray;
</script>
</body>
</html>
 
Joined
Nov 13, 2020
Messages
302
Reaction score
38
No problem, I was going to post that there aren't any numbers between 5 and 6 unless you're using decimals.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top