Choose the outermost elements from an array and combine them

Given an array such as [0,1,2,3,4,5], where the length is always even.

How can I select and pair elements starting from the leftmost and rightmost positions all the way to the center?

For example, in the array above, it should result in [[0,5],[1,4],[2,3]]

I have already attempted a solution which can be seen here

const arr = [0,1,2,3,4,5]

const result = []
const possibleMatches = arr.length / 2

for (let x = 0; x < possibleMatches; x++) {
  result.push([arr[x], arr[arr.length - x - 1]])
}

console.log(result)
//[ [ 0, 5 ], [ 1, 4 ], [ 2, 3 ] ]

However, are there better approaches than using a for loop? Perhaps utilizing one-line arrow functions?

Answer №1

element, you can divide the array into two halves using Array.splice. Afterward, iterate over the array with the map method and apply the same logic as in your for loop to access elements from the "right" side:

For example:

const arr = [0, 1, 2, 3, 4, 5]

const result = arr.splice(0, arr.length / 2).map((e, i) => [e, arr[arr.length - i - 1]])

console.log(result)

Answer №2

One way to create a new array with half the size of the original is by using `Array.from()` and selecting values from both ends of the original array:

const arr = [0,1,2,3,4,5]

const result = Array.from(
  { length: Math.ceil(arr.length / 2) },
  (_, i) => [arr[i], arr[arr.length - 1 - i]]
)

console.log(result)

If your environment supports it, you can also use Array.at() to achieve this without needing to calculate the length:

const arr = [0,1,2,3,4,5]

const result = Array.from(
  { length: Math.ceil(arr.length / 2) },
  (_, i) => [arr.at(i), arr.at(-i-1)]
)

console.log(result)

Answer №3

rearrange the array by flipping and merging its halves.

check out this single line of code solution:

const numbers = [0,1,2,3,4,5]

const arrangedArray = numbers.slice(numbers.length / 2 * -1).reverse().map((element, index) => [numbers[index],element])
const halfLength = numbers.length / 2

console.log(arrangedArray)

Answer №4

Implementing a straightforward for loop that iterates from both ends

const arr = [0, 1, 2, 3, 4, 5];

let results = [],
  start = 0,
  end = arr.length - 1;
  
for (; start < end; start++, end--) {
  results.push([arr[start], arr[end]]);
}

console.log(JSON.stringify(results));

or utilizing a while loop

const arr = [0, 1, 2, 3, 4, 5];

const output = [];

while (arr.length > 1) {
  output.push([arr.shift(), arr.pop()]);
}

console.log(JSON.stringify(output));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The MaskedInput text does not appear properly when it is passed through the props

Currently, I am facing an issue with a Material UI OutlinedInput along with the MaskedInput component from react-text-mask. Everything works fine when I input text initially and the element is not in focus. However, upon closing and reopening the Dialog wi ...

Using JavaScript to launch a new window for a specific folder

When opening a popup window with a specific URL, I typically use the following code: $("#OpenFolder").click(function () { var url = "https://stackoverflow.com"; windowObjectReference = window.open(url, "ModulesList", " ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

SVG: Altering the dy attribute has no impact on the overall height of the bounding rectangle for the parent text

We are striving to align a group of tspan elements both vertically and horizontally. However, the parent container is not taking into consideration dy values. This lack of consideration is leading to alignment issues. If you adjust the dy values in this ...

Text will scroll within a DIV when a key is pressed

Is there a way to implement a scroll effect on the div using the SPACE key? I would like the first span to move out of sight while the rest become visible when the key is pressed. HTML <div class="scroll-div"> <span class="item1">Lorem ipsu ...

Transmitting FormData from Angular to a .NET MVC Controller

Here's my perspective: <form ng-submit="onFormSubmit()"> <div class="form-group"> <label for="Movie_Genre">Genre</label> @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Na ...

Working with JSON Arrays in PHP - How to Retrieve a Value within the Array

I am facing an issue with a JSON array received through an API. My challenge is to display the data, but the values are not consistently located within each item. Below is a snippet of the JSON response - just a part of it as the file is extensive: "stand ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Creating a table that includes a textbox

Having some experience coding in php, I'm venturing into the world of js with a new project. My goal is to create a straightforward order form, where each line includes a text box for quantity, product name, and price. The price should be pulled from ...

"Error: The $ variable is not defined" - encountered while working with a date-time picker in Jade/Pug

I am attempting to implement a date/time picker in jade/pug that resembles the example provided on this page: . I am working with a Node/express js server. However, when I click on the glyphicon-calendar icon, the calendar fails to display. I have already ...

Tips for replacing or deleting all text that isn't within parentheses using JavaScript

As a complete beginner in the world of Regex, I am attempting to extract only the text inside the parenthesis while discarding everything outside of them. For instance, consider this scenario: Hello,this_isLuxy.(example) The desired output should be as ...

Error with compiling due to passing an array as a parameter in Visual C++ 2010

I'm currently in the early stages of learning programming, and I've recently been introduced to QuickSort algorithms. In my quest to understand this concept better, I attempted to pass an integer array as a parameter to a function called quickSor ...

The ChartJS is failing to display the pie chart

Encountered an issue while trying to load the chart: Error: Uncaught TypeError: n is not a function at t.render (Chart.min.js:10) at Object.callback (Chart.min.js:10) at Object.advance (Chart.min.js:10) at Obj ...

array size is not being accurately reported

As I try to make sense of this code, something seems off. It appears to be a straightforward portion of a promise chain. let flightName = []; let guidArr = []; Promise.all(guidArr) .then(values => { for(var a = 0; a < values.length; ...

Using jQuery to rearrange an ordered list by moving items with a specific class to the top

Is there a way to use jQuery to rearrange ordered list items with a specific class and move them to the top of the list? Consider the following snippet of HTML code: <div id="notice">click here</div> <ul> <li>Coffee</li> ...

Using a PHP variable to store a JavaScript variable for generating a dynamic meta description on a webpage

I have successfully executed an AJAX request in CodeIgniter. This request retrieves data from the database and displays it on the same page. I am looking to create a dynamic meta description, where I want to incorporate a specific field value from the data ...

Effortlessly create a seamless transition in background color opacity once the base image has finished

I've set up a div with a sleek black background. Upon page load, I trigger an API request for an image, which is then displayed in a secondary div positioned behind the main one. After this, I aim to smoothly transition the overlaying div's opaci ...

Searching for a specific bus stop within an array based on a designated route

There's an issue at hand. We have a route with several bus stops. We need to determine the next stop on this route. The "_stopNum": "1" indicates that the stop is the first one on the route. Take a look at a stop example: { "route": [ { ...

Html Canvas Overlay that allows content underneath to remain interactive

Trying to layer the canvas outlined in red over the div with a black border that is currently underneath. The canvas should match the size of the div, and I need to be able to interact with buttons and text beneath it. I've been at this for 48 hours a ...