Employing the unshift method on a two-dimensional array

I've been experimenting with the unshift function on a multidimensional array, but I'm having trouble getting it to work as expected.

Using shift works fine and does what I need, but unshift doesn't behave properly.

Here is the array I'm working with:

[ [ '487', 'RINGING' ], [ '477', 'RINGING' ] ]

When I try to use unshift on it, it gives me this output:

[ [ '487', 'RINGING' ], [ '477', 'RINGING' ], 2 ]

What I actually want is to move the '477' array to the beginning like this:

[ [ '477', 'RINGING' ], [ '487', 'RINGING' ]]

The code snippet I am using:

var channelArrStatus = [ [ '477', 'RINGING' ], [ '487', 'RINGING' ]];

function monitor_channel(event, channel) {
if (event.device_state['state'] === "RINGING") {
      var name = "User_487";
      var status = "NOT_INUSE"
      var index = 0;
      if (channelArrStatus.length === 0) {
        var chanar = new Array(name, status);
        channelArrStatus.push(chanar);
      } else {
        var found = false;
        for (var i in channelArrStatus) {
          var channelArrStatusElem = channelArrStatus[i];
          if (channelArrStatusElem[0] === name) {
            index = i;
            found = true;
            if (channelArrStatus[index][1] !== "DND") {
              channelArrStatus.push(channelArrStatus.unshift());
              setTimeout(function () {
                channelArrStatus[index][1] = status;
              }, 10000);
            }
          }   
        }
      }
    }

I'm struggling to achieve the desired result of moving an array to the beginning using unshift as shown above.

Any suggestions?

EDIT:JSFiddle

Answer №1

The .unshift() method adds an item to the beginning of an array and returns the new length of the array, which is 2 in this scenario.

To achieve your desired result, you can either use:

channelArrStatus.push(channelArrStatus.shift()); // no un-

or

channelArrStatus.unshift(channelArrStatus.pop());

It is recommended to use literal notation over the Array constructor and avoid using for in loops with arrays.

Answer №2

Here is a simple way to update an array

 channelArrStatus.push(channelArrStatus.unshift());

By using this method, you are inserting the length of array at the end. If you wish to insert an element at the beginning of the array, use unshift.

channelArrStatus.unshift(element);

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

Tips for triggering a click event on a DOM element using Angular 2

How can I automatically load a component upon loading? <app-main id="tasks" [(ngModel)]="tasks"></app-main> Here is the function call from JavaScript: public tasks; ngOnInit() { this.tasks.click(); } I have attempted using document.getE ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

Organize a list using custom span values with JavaScript

<ul id="CoreWebsiteTopHeader_6_list"><li><a class="navigation" href="/seller"><span class="editableLinks" data-id="32638" data-sort="110">Seller</span></a></li><li><a class="navigation" href="/about">&l ...

Unable to display image in jqGrid binary format

In our system, we use a standard function to retrieve images stored as binaries in the database, and this function works seamlessly throughout the entire system. However, when implementing jqGrid, I encountered difficulties using the existing structure as ...

Design a dynamic dropdown feature that is triggered when the chip element is clicked within the TextField component

Currently, I am facing difficulties in implementing a customized dropdown feature that is not available as a built-in option in Material UI. All the components used in this project are from Material UI. Specifically, I have a TextField with a Chip for the ...

Using C++ and a for-loop to store data in an array

Currently delving into the basics of C++ and tackling arrays, I'm faced with a program assignment for one of my classes. The task involves taking user input to calculate work hours over a specified period. The user provides the number of days worked, ...

Creating a Sudoku game board using underscore templates

Currently, I am in the process of constructing a Sudoku board using underscores templating. However, I have hit a roadblock when it comes to tackling the mathematical aspects necessary for deriving the table structure. My approach involves utilizing a 1d ...

Generate unpredictable visual elements on the canvas using JavaScript

Greetings everyone, I am currently working on creating a javascript game using canvas. My goal is to implement random enemy objects in the game. I have come across this example for spawning: JSFiddle Demo Is there a way to load image(s) instead of balls f ...

Error: The module '/@modules/vue.js' does not export a 'default' value as requested by the syntax

I'm encountering an issue with Vee Validate form validation in Vue.js. As a beginner, I am struggling to grasp the import syntax. After installing vee-validate using npm i vee-validate --save and placing it in my node_modules directory, I proceeded to ...

"Using jQuery to selectively hide a div and eliminate the required field

Is there a way to remove the "required" attribute from hidden fields while keeping it required in visible fields? In this form created with Django framework, I need the required field to be removed when a specific option is selected. For instance, if the ...

Converting a Json array to a .NET object: An Easy Guide

I need help with parsing a JSON string that contains an array of coverage values. string jsonData = @"{ ""plans"": [ { ""plan_code"":""UL500"", ""plan_name"":""Unlimited 500M"", ""days"":1, ""limit"":500, ""coverage"": [ { ""country"":"" ...

Manipulate data within multidimensional array by adding or requesting values

I have created a multidimensional array in the following way: var languageArray = {}; $('#language li a img').each(function(index) { var helperArray = []; helperArray.push(langi); helperArray.push(getnumber); languageArray.push(h ...

The order of CSS precedence shifts even when the class sequence is the same

In my development setup, I have a react component that is embedded within two distinct applications each with their own webpack configurations. Within the component, I am utilizing a FontAwesome icon using the react-fontawesome library: <FontAwesom ...

What is the method for applying multiple criteria to filter an array in Vuejs?

const app = new Vue({ el: '#app', data: { search: '', itemsList: [], isLoaded: false, selectNum: status, userList: [{ id: 1, name: "Prem", status: "ok" }, { id: 2, ...

Attempting to develop a version of Space Invaders utilizing kaboom js on the Replit IDE platform, encountering some difficulties

I'm currently experiencing an issue with changing the scene to the lose state when the player runs out of time or aliens successfully invade. However, I keep encountering this error: Error: scene not found : lose Due to space limitations, I am unabl ...

Combining items in JavaScript using a shared key

Is there a way to combine 4 separate arrays of objects into one big object based on the keys inside an object? For example: OUTPUT: What I want to achieve. [ { "bugId": "", "testerId": "", "firstName": "", "lastName": "", "country": " ...

The Consequences of Using Undeclared Variables in JavaScript

What is the reason behind JavaScript throwing a reference error when attempting to use an undeclared variable, but allowing it to be set to a value? For example: a = 10; //creates global variable a and sets value to 10 even though it's undeclared al ...

"Need to refresh localStorage in VueJS after navigating back with this.$router.go(-1)? Here's how

Below is my Login.vue code: mounted() { if (localStorage.login) this.$router.go(-1); }, methods: { axios.post(ApiUrl + "/login") { ... } then(response => { ... localStorage.login = true; this.$router.go(0); ...

Max value determined by a variable within a for loop

UPDATE: Revised code provided. In my Node.js JavaScript project, I am creating a script to iterate through a dataset obtained by web scraping. The main goal of this algorithm is: 1) Examine the player table for the presence of the player's name in a ...

The Ajax submit button is only operational for a single use

Check out my basic HTML form and JS setup: <body> <form> <label for="usrtext">Type your text here:</label> <br /> <textarea name="usrtext" id="usrtext" rows="25" cols="100"></textarea> ...