0

Suppose I have an array like such:

var test_array = [0.1, 2.1, 0.7, 5.4, 3.2, 1.6];

I basically want to grab the first 2 values in the array, place them into 2 separate variables and then move on to the next step, like so:

var test_array = [0.1, 2.1, 0.7, 5.4, 3.2, 1.6];
test_array.sort();
for (let i=0;i< test_array.length -1; i++) {
   var j = i + 1;
   var pt_one = test_array[i];
   var pt_two = test_array[j];
   console.log("pt_one = " + pt_one);
   console.log("pt_two = " + pt_two);
   
}

Is there a more efficient way to do this? Could the forEach() method be used somehow?

2
  • forEach might be a bit better, but not by much. Your current code is fine. Commented May 19, 2021 at 22:45
  • 1
    There's little need for the j variable, just write test_array[i+1] Commented May 19, 2021 at 22:48

2 Answers 2

1

You could try this using forEach:

test_array.forEach((n, i, arr) => {
  var [pt_one,pt_two] = test_array.slice((arr.length - i) * -1);
})
Sign up to request clarification or add additional context in comments.

1 Comment

This is almost perfect except for the last iteration puts pt_one = 100; pt_two = undefined;
1

It may not be much better, but your length is incorrect anyways. I thought you might want to see two increments at a time:

let test_array = [0.1, 2.1, 0.7, 5.4, 3.2, 1.6, 10, 100], pt_one, pt_two;
test_array.sort((a, b)=>a-b);
for(let i=0,n=1,l=test_array.length; i<l; i+=2,n+=2){
  pt_one = test_array[i]; pt_two = test_array[n];
  console.log('pt_one = '+pt_one); console.log('pt_two = '+pt_two);
}

I noticed you will have a problem with that sort, as well.

1 Comment

More concise, but not quite what I am looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.