Locate an array within a Multidimensional array and relocate it to the starting position

I've been attempting to figure out a solution for moving a specific array within another array to the beginning.

The problem I'm encountering is that the code I was using, as suggested in a previous question, only removes the last value and places it at the front:

channelArrStatus.unshift(channelArrStatus.pop());

The issue arises when the values are different each time; in such cases, I need it to identify which array meets certain conditions and move that particular array to the start of the main array.

Desired Outcome

Initial Array - [ '477', 'RINGING' ] :

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

Resulting Array:

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

Current Behavior!

Before Reordering:

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

After Reordering:

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

What's happening now doesn't match my intended logic. Here's a simplified version of the code:

var channelArrStatus = [ [ '477', 'RINGING' ], [ '487', 'NOT_INUSE' ], [ '488', 'RINGING' ]];
var state = "NOT_INUSE";

function testArray(){
if (state === "NOT_INUSE") {
      var name = "487";
      var status = "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") {
              setTimeout(function () {
                channelArrStatus[index][1] = status;
                if(channelArrStatus[index][1] === status){
                channelArrStatus.unshift(channelArrStatus.pop());
                document.write(channelArrStatus);
                }
              }, 4000);
            }
          }   
        }
      }
      }
      }

      testArray();

JSFiddle Example

I understand why it's not working as expected, and I've tried various approaches to rearrange the identified array to the front. Any suggestions?

Answer №1

Opt for the unshift method combined with splice:

let list = ['apple', 'banana', 'cherry', 'date'],
    position = list.indexOf('cherry');
Array.prototype.unshift.apply(list, list.splice(position, 1));

Answer №2

This particular suggestion utilizes a custom function to search for specific data and determine the appropriate index for modifying the array.

var data = [['487', 'RINGING'], ['477', 'RINGING'], ['488', 'RINGING']],
    index = function (array, search) {
        var index = -1;
        array.some(function (a, i) {
            if (a.every(function (b, j) { return b === search[j]; })) {
                index = i;
                return true;
            }
        });
        return index;
    }(data, ['477', 'RINGING']);

~index && data.unshift(data.splice(index, 1)[0]);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

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

To effectively delete the <li> element using JavaScript, make sure to eliminate the associated array object as well

I am in the process of designing a compact landing page that will randomly select a city from user input to determine the next trip destination. When the user types in the city name into the input field, everything functions correctly - a new list element ...

Generate PHP arrays containing data on the number of orders and dates extracted monthly from an SQL database

I have a database table named 'orders' which contains multiple rows with different date entries. My objective is to create a visual representation in the form of a graph displaying the number of orders per month. To achieve this, I need to const ...

Solving Addition and Subtraction Errors in Javascript/Jquery

Upon running the script below, it aims to calculate the height of the browser, as well as the heights of both the header and footer, subtracting them from the initial browser height: var a = $(window).height(); alert (a); var b = $('#header').cs ...

Failure to register Express Route

I am currently using express and facing some challenges with creating routes using express.Router. Below is my index.js file (npm main file): require('dotenv').config() const express = require('express') const loaders = require('. ...

Export information from variables, lists, and dictionaries to a csv file

I am in the process of generating a csv file containing user information. So far, I have successfully created a csv file for variables like "name," "surname," and age. However, I also have data stored in lists and dictionaries with unknown lengths that I d ...

Creating a fresh array by applying a filter and assigning keys

I am facing an issue with my array structure, it looks like this, [ [ "Show/Hide", "P000", "MAX-CT05 FVM2-", "S", 1532, -9.5929406005, null, null, ...

Guide on creating a toggle effect for a div with querySelector and addEventListener

I utilized the email and password divs provided by Bootstrap. The CSS for the id dropdownlogin includes display: none; in this post, I hope that I have shared adequate information. <script> document.addEventListener('DOMContentLoaded', ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

Which design pattern would be best suited for monitoring the completion of multiple ajax requests?

In my code, I have combined 3 separate ajax calls in one function along with checkAjaxCompletion method to monitor each ajax completion flag. The current approach involves sending multiple independent ajax calls and using an interval method to continuousl ...

Utilize D3 to Rotate Text within an SVG in Circular Motion, Following by Self-rotation

In my visualization, the labels are arranged around the center of a circle by rotation. However, this results in the labels on the left side of the circle appearing upside down. Is there a way to rotate the labels on the left side independently after the i ...

Using TypeScript to define callback functions within the Cordova.exec method

I'm encountering an issue with the TypeScript definition for Cordova. The codrova.d.ts file doesn't allow for any function arguments in the success-callback and error-callback. To better illustrate my problem, here's a small example: Here ...

preserving the status of checkboxes based on an array of binary values

I am trying to figure out how to restore the state of checkboxes in an ORACLE APEX tabular form. The selection is made in the first column using the APEX row selector f01. After saving the checkbox state in a collection and then transferring it to an arra ...

Responsive left and right image styling in CSS and HTML

I have designed a landing page with fixed left and right images and content in the middle. It looks fine on desktop view, but on mobile view, the images are overlapping the content. How can I resolve this issue? <div class=" ...

Having trouble resolving this issue: Receiving a Javascript error stating that a comma was expected

I am encountering an issue with my array.map() function and I'm struggling to identify the problem const Websiteviewer = ({ web, content, styles, design }) => { const test = ['1' , '2'] return ( {test.map(item => { ...

I am unable to retrieve the value stored within a function

Below is the code snippet : let namesList = ref([]); const GetFormData = (payload) => { return new Promise((resolve, reject) => { api .get("api.php", { params: { search: payload } }) .then((response) => { data. ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

What is the best way to stop form submission in AngularJS when submitting the form by pressing the enter key?

I have implemented validation on my form (which consists of only two fields) but I am struggling to figure out how to prevent it from being submitted with empty data. The current flow is as follows: Upon pressing the enter key, the student's name and ...

Guide for setting up multiple checkbox event listeners with jQuery

I currently have 2 checkboxes on my form: <form action=""> <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I own a bike<br> <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I ...

Broken links detected in the Full Page Navigation menu on a one-page website

The hyperlinks on this particular page seem to be malfunctioning despite the fact that the li.a tags are correctly targeting specific section IDs. Markup: <header> <a href="#0" class="nav_icon"><i></i></a> </header> ...