Retrieve evenly spaced keys from the center of an array

I am working with some JavaScript code that is meant to extract the first and last elements from an array, then incrementally include the remaining elements.

For example:

var numbers = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'];
var values = [];
values.push(numbers[0]); // get first
values.push(numbers[numbers.length-1]); // get last
numbers = numbers.slice(1, numbers.length-1); // remove first and last elements
console.log(numbers);
var interval = 2;
for (var i = interval; i < numbers.length; i+=interval) { // retrieve every 2nd item
  values.push(numbers[i]);
}
console.log(values);

This code will yield:

["One", "Ten", "Four", "Six", "Eight"]

If we re-order these elements, we get:

["One", "Four", "Six", "Eight", "Ten"]

However, if the data set gets updated to include 'Eleven', it will result in:

["One", "Eleven", "Four", "Six", "Eight", "Ten"]

Re-ordering would give:

["One", "Four", "Six", "Eight", "Ten", "Eleven"]

The issue arises when items like Ten and Eleven end up next to each other without equal spacing as the rest of the elements.

To address this, I attempted to check if the array length is even and adjust the interval accordingly by making it odd, as shown below:

if (interval % 2 != 0)
    interval = interval + 1;

However, there are situations where an uneven distribution still occurs due to how the array is sliced and processed. This leads to an element being positioned incorrectly in relation to the others based on the interval chosen.

How can I overcome this challenge? Essentially, I want to consistently select the first and last elements, while evenly distributing the middle elements based on a specified interval parameter.

Answer №1

To create an evenly spaced array, you can calculate the index accordingly.

function generateArrayValues(array, count) {
    var lastItem = array.pop(),
        values = [];

    for (i = 0; i < count - 1; i++) {
        values.push(array[Math.floor(i * array.length / (count - 1))]);
    }
    return values.concat(lastItem);
}

console.log(generateArrayValues(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'], 5));
console.log(generateArrayValues(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven'], 5));

If you are aiming for a more equitable spacing, consider exploring the Euclidean algorithm, or opt for the Bjorklund's algorithm, which distributes spaces uniformly around the items. Alternatively, you can investigate the concept of Euclidean's rhythm.

Answer №2

In order to provide a solution, it's important for you to state your objective clearly. It appears that you're aiming for evenly distributed values, with the inclusion of both the first and last items. However, you haven't explicitly confirmed this requirement nor have you indicated if intervals of 2 hold any significance in your case.

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

Warning from Vue: Steer clear of directly changing a prop as it will be replaced whenever the parent component undergoes re-rendering

I've been diving into Vue.js, but I'm encountering an issue. Every time I try to click on the "edit age" or "change my name" button, I get the following error message. [Vue warn]: Avoid mutating a prop directly because the value will be overwrit ...

Issue arises when Protractor is unable to compare a variable with a web element due to unresolved promises

My strategy for this examination was to extract the inner text of an element, modify it, and then verify that the change had taken place by comparing the element with the variable. var fixedValue = element(by.xpath('/html/body/section/div/section/sec ...

Custom sparkline array

In working on my sparkline chart, I have the following code snippet: <div sparkline="" values="4,4,7,5,9,6,4" data-type="line" data-height="80" data-width="100%" data-line-width="2" data-line-color="#dddddd" data-spot-color="#bbbbbb" data-fill-c ...

What is the best way to reverse the order of objects in a JSON parsed object?

In my possession is an object {"5":"5","4":"4","3":"3","2":"2","1":"1","-1":"P1",-2":"P2"} Utilizing this specific function to interpret the elements: function floormake(inobj) { var levels = ''; var obj = JSON.parse(inobj); levels + ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

"In the shadows, the .toLowerCase() method of undefined is failing without making a sound, yet the code

It seems that letting things fail in the background is necessary for this example to work consistently. Is there a way to work around this issue? There are instances where I need to check a div with a data-attribute on certain pages and add a class if it ...

Warning: The alert box must be closed repeatedly

When checking the value of a form field, an alert box pops up if the value is more than 5. However, I've noticed that after filling in the field once, the alert box needs to be closed multiple times if entering another value above 5. This issue has no ...

Transferring the "key" and "values" data from a JSON object to a perl script

I am currently working on developing a shopping cart application. All the items stored in the shopping cart are kept within a JavaScript object called Cart, with data structured like {"sku"=quantity}. For instance: Cart={"5x123"=1,"5x125"=3} At this ...

The MongoDB object type is not stored

Let me share my customized user schema below. var userSchema=mongoose.Schema({ //name:{type:String}, username: {type:String, required:true, unique:true}, password: {type:String, required:true}, habit: {type:Object, required:true} }); Howev ...

Transmit data from the Windows Communication Foundation to JavaScript

Looking to invoke the WCF service through JavaScript, utilizing AJAX? Check out this resource: Calling WCF Services using jQuery Here's my query: Is there a method to retain some JavaScript-related data after making a request, and then transmit inf ...

Transform a continuous string into an associative array with multiple dimensions

I am facing a challenge where I need to extract values from a string without any delimiting characters and create an associative array out of it. Let's take a look at an example string: *01the title*35the author*A7other useless infos*AEother useful i ...

Tips for improving the speed of array iteration in Ruby

I am dealing with multiple CSV files containing product names and prices. Some products may be included in one or both files. My task is to determine the highest and lowest price for each product across all files. To accomplish this, I have merged the pro ...

Categorizing JavaScript objects based on a shared value

I have a query that retrieves location-based data from my database. After performing the query, I receive a collection of objects (which I consolidate into a single object and use console.log() to inspect its contents). Each object represents a user' ...

"Encountering a Node.js error while trying to open an image for the second

My goal is to use Node to take a screenshot of the user's screen on all displays and save everything in a single image. Everything works fine when I call it for the first time, but if I try to call it a second time without restarting the server, an er ...

Generating Speech from Text using jQuery API in HTML

Can a website be created to detect textbox text upon longClick by the user, and function across various browsers? The site should also have mobile compatibility. Appreciate any help! ...

Guide on submitting a form using a custom AJAX function based on the id or class parameter

Instead of writing an ajax call every time with changing API URL, post method, and form id or class name based on the page, I am attempting to develop a custom function that can manage the API call based on the provided parameters. The essential parameters ...

Guide to extracting the values from a newly added table row with the onchange event

Seeking help for a complex issue I'm facing with my ajax function. The function retrieves data from a database and appends it to a table, sometimes resulting in multiple rows being appended due to multiple records retrieved. My challenge is extracting ...

The Jquery confirmation dialogue does not seem to be functioning properly within the Content Place Holder

I've encountered an issue with a JQUERY Confirm dialogue where it works perfectly fine until I place it on a page that is within a masterpage. The confirm alert pops up for a split second and disappears. window.onload = function() { $("#ehi").cli ...

Spin an object along any axis in Three.js, similar to how the moon orbits the Earth

After attempting numerous solutions to the problem, the object continues to rotate around its own axis without any translation. ...

Guide on clicking an element within a hidden iframe using Python Selenium

I am facing a challenge in finding elements within an iframe tag. Surprisingly, the HTML source does not contain any iframe tags. However, upon inspecting the element, I can see that there is indeed an iframe tag present. How can I tackle this issue using ...