Manipulating Arrays in order to delete an index

I have been working on a function to manipulate arrays...

 var myArray = [2, 1, 1, 1, 1];

and I want to transform it into this

[3, 1, 1, 1]

The function I created accepts 3 parameters

  1. ArrayToProcess - the array that will be processed
  2. indexTarget - the selected value defined by index
  3. morphToValue - the value I want the selected value to become

My main goal is to accept the indexTarget, for example

myFunction(myArray, 0, 3); //myArray is [2, 1, 1, 1, 1]

The objective is for the function to loop over the myArray and add numbers in the array until it reaches the morphToValue resulting in [3, 1, 1, 1]. It removes the 2 at the first index and 1 at the second index to add 3. It also subtracts any excess number from the morphToValue

Another example would be to transform the array

var myArray = [2, 1, 1, 1, 1];

into this

[2, 1, 3];

by calling myFunction like this

myFunction(myArray, 2, 3);

How can I achieve this? I also want the function to restart iteration from the beginning of the array if the indexTarget is set to the last index of the array, resulting in

var myArray = [2, 1, 1, 1, 1];

it should become

[1, 1, 1, 3]; //when I invoke myFunction(myArray, 4, 3);

Please let me know in the comments if you need further clarification...

This is the code I have tried so far http://jsfiddle.net/eESNj/

var myArray = ['2', '1', '1', '1', '1'];

indexPurge(myArray, 0, 3);

function indexPurge(haystack, indexTarget, morphToValue) {

    var toIntHaystack = [];

    for (var i = 0; i < haystack.length; i++) {
        toIntHaystack.push(parseInt(haystack[i]));
    }

    console.log(toIntHaystack); //before

    var i = 0;

    var purgedValue = 0;

    do {
        console.log(i + ' - ' + toIntHaystack[i]);
        purgedValue += toIntHaystack[i];
        toIntHaystack.splice(i, 1);
        if (purgedValue >= morphToValue) {
            break;
        }
        i++;
    } while (i < toIntHaystack.length);



    toIntHaystack.splice(indexTarget, 0, morphToValue); //after
    console.log(toIntHaystack);

}

Answer №1

Check out my updated approach that is optimized for faster performance compared to the splice method:

function adjustIndex(index, length) {
    return index % length; 
}
function fixStartingPoint(index, length) {
    return (index < length) ? 0 : (index % length);
}
function rearrangeArray(inputArray, startingIndex, targetValue) {
    var arrayLength = inputArray.length;
    var total = 0;
    var endIndex = 0;
    while ((total < targetValue) && (endIndex < arrayLength))
        total += inputArray[adjustIndex(startingIndex + endIndex++, arrayLength)];
    if (endIndex == arrayLength) return [total];
    var resultArray = [];
    for (var i = fixStartingPoint(startingIndex + endIndex, arrayLength); i < startingIndex; i++)
        resultArray.push(inputArray[i]);
    resultArray.push(total);
    for (var i = startingIndex + endIndex; i < arrayLength; i++)
        resultArray.push(inputArray[i]);
    return resultArray;
}

Answer №2

I was able to find a solution to my own issue. Hopefully, this solution can assist someone else facing a similar problem.

http://jsfiddle.net/YUdJL/

var myarrayx =  [1,1,3]; //5

function adjustArray(myarray, index, target){

    //accumulate value on the array to reach the target value
    var accu = 0;
    for(var i = 0; i < myarray.length; i++){
        var thisIndex = myarray[i];
        for(var j = 0; j < thisIndex; j++){
            if(accu != target){
                myarray[i]--;  
                accu++;
            }
            else{
                break;
            }
        }
    }

    //remove any zeros from the array
    for(var k = 0; k < myarray.length; k++){
        if(myarray[k] == 0){
            myarray.splice(k, 1);
        }
    }

    //check if the target index is still available
    if((myarray.length - 1) > index){
        //index is no longer available, so just push the target
        myarray.push(target);
    }
    else{
        //insert the element at the desired index
        myarray.splice(index, 0, target);
    }

    return myarray;
}

console.log('----'+adjustArray(myarrayx, 0, 2));

Answer №3

Give it a shot

let array = [2, 1, 1, 1, 1];

function customFunction(arr, idx, target) {
    let copyArr = arr.slice(0);
    let count = 0;
    let i = idx;
    while (count < target && arr.length) {
        count += copyArr.splice(i, 1)[0];
        if (i == arr.length - 1) {
            i = 0;
        }
    }
    if (i == idx) {
        copyArr[idx] = count;
    } else {
        copyArr.push(count);
    }
    return copyArr;
}

console.log(customFunction(array, 0, 3));
console.log(customFunction(array, 2, 3))
console.log(customFunction(array, 4, 3))

Check out the demo: Fiddle

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 yarn installation process is not utilizing the latest available version

Working with a custom React component library my-ui hosted on a personal GitLab instance. In the package.json, I include the library like this: "my-ui": "git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6 ...

What steps can I take to display a download button when a file is clicked on?

As a backend developer, I usually don't delve into JavaScript tasks, but I have a simple query for JavaScript developers that I need help with. Here is my question: I am trying to display a download button when a specific file is clicked using jQuery ...

What is the best way to record and share a video with jquery and laravel?

Is there a way to grant users access to record videos within an application and then upload them after previewing? I've been able to successfully record and download a video, but now I'm unsure of how to proceed with uploading it to the server. ...

Is there a way to use JavaScript to modify the position of a div element

Can we adjust the div position using CSS (absolute or relative) with JavaScript? Here's an example code snippet: <div id="podpis" style="margin-top: 2rem;"> <div class="invoice-signature"> <span><?=$xml->sanitiz ...

Could we confirm if this straightforward string is considered valid JSON data?

There are numerous intricate questions on Stack Overflow about whether a complex structure is considered valid JSON. However, what about something much simpler? "12345" Would the provided code snippet be considered valid JSON? ...

When attempting to deserialize a 2D array in JSON, it unexpectedly returns as a string instead of

I am trying to figure out how to deserialize the JSON string provided below into a two-dimensional array object using JavaScript. Whenever I attempt to use JSON.parse or eval, it ends up getting converted into a string format. Currently, I am utilizing D ...

These JS and Perl scripts may encrypt the same data, but they generate different results. Isn't it expected for them to produce identical output?

Two different programs, one in Javascript and the other in Perl, were designed to accomplish the same task with identical input data. Nevertheless, the output generated by these programs varied. The issue stemmed from using JavaScript on the client side to ...

the power of using keywords and prototypes

Greetings! I am currently delving into the realm of JavaScript, hailing from a C++ background. The transition has proven to be quite perplexing for me. Below is a snippet of code that I have been troubleshooting: var someArray = []; nameCompare = function ...

Having trouble connecting to the http json service in AngularJS

I recently started learning angularjs and I'm facing an issue with my code. There seems to be a flaw in the code and I'm uncertain about it. From a java perspective, the httpController has a nested function defined inside. Below is the code sn ...

Steps to remove a script upon clicking a button?

On my website, I have integrated a plugin called manychat using a <script>. However, when I click on the Drawer Cart, the manychat symbol overlays over the checkout button, which is not visually appealing. Is it possible to unload this script when ...

"Troubleshooting Bootstrap nav-pills' failure to update displayed content

I'm currently working on creating a dynamic navbar that updates the content based on which navigation pill is selected. For some reason, the content in my div.tab-content isn't changing as expected... Here is an example of the code I am using: ...

Python - scrabble letter tally

I'm trying to create a simple Python program for Scrabble that can calculate the score of a given word. As a newbie to Python, I'm still working on understanding how to manipulate lists effectively. My idea is to assign each letter a specific va ...

Attempting to design a customized tooltip for an SVG element embedded within the HTML code

Recently, I've delved into Js with the goal of creating an interactive pronunciation guide using inline svg. If you're curious to see what I've done so far, check it out here. My current focus is on incorporating basic styled tooltips that ...

The URL may change, but Angular remains on the same page without navigating

I am encountering an issue with 2 links in my application. The first time I click on any one of them, it navigates to the corresponding page without any problem. However, when I click on the second link after that, the URL changes but the navigation does n ...

Troubleshooting the Expanded Row Problem in 'angular-ui-grid'

Following a recent update, the expanded row feature in Google Chrome (version 77) is not functioning correctly compared to version 76. Prior to the update, the expanded rows in 'angular-UI-grid' worked well on all browsers including Mozilla Firef ...

Passing parameters to Next.js pages

Here is my function: export async function getServerSideProps({ req }: any) { const user = ( await axios.get("http://localhost:4000/api/auth/status", { withCredentials: true, headers: { Cookie: `connect.sid=${req.cookies["c ...

Learn the process of developing a web client application using Node.js and NPM similar to the AngularJS tutorial

I am new to nodejs, npm and angularjs. I recently explored the angularjs tutorial project available at https://github.com/angular/angular-phonecat.git. This project has been really interesting for me as it demonstrates how easy it is to manage modules wi ...

methods for efficient set computations

I have a collection of sets in the format (a,b) which are as follows: (2,4) (1,3) (4,5) (1,2) If I am given a pair like <2,1>, I want to identify all sets in the collection where 2 or 1 is the first element. In this case, it would be (2,4), (1,3), ...

"Using ng-include with ng-show doesn't seem to be functioning properly

I am facing an issue with my Angular app where the template is getting too large. I would like to split it and utilize the ng-include directive, but I am struggling to get it to work properly. current state of template.html <div class="edit-ob ...

What does the `Class<Component>` represent in JavaScript?

Apologies for the lackluster title (I struggled to think of a better one). I'm currently analyzing some Vue code, and I stumbled upon this: export function initMixin (Vue: Class<Component>) { // ... } What exactly does Class<Component> ...