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

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

Instructions on creating a countdown timer that reveals a hidden div once it reaches zero, remains visible for a set period, and then resets

I created a countdown timer that displays a div when the timer reaches zero. However, I am struggling with getting the timer to reset and start counting down again after displaying the div. For instance, if I set the timer for 7 days and it reaches the de ...

Inject the JSON data fetched through AJAX into Datatables

I have been successfully using the datatables plugin to populate multiple tables with data. However, I realized that instead of making separate AJAX calls for each table, I could optimize by fetching the data once and storing it in a variable to be used by ...

VueJs Ellipsis Filter: Enhance Your Texts with

Using Vue.JS, I am dynamically injecting text content into a DOM element. <article>{{ movie.summary }}</article> My goal is to implement an auto-ellipsis filter. Essentially, the code would look like this: <article>{{ movie.summary | e ...

Error: Uncaught TypeError - Unable to change value of 'innerHTML' for null object in VueJs

I have been encountering a similar problem to others, but despite trying the solutions provided in previous questions, I am unable to resolve it. In my <template>: <modal name="MyModal" > <span class="myClass" id="visible">visible< ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

Show segments of video stream on page using node.js

I am currently exploring Node.js and trying to understand how streams work, so please bear with me if I seem a bit unclear. After reading some beginner notes on streams, I decided to test it out. In my project files, specifically in public/images/videos/S ...

Using Firebase to interact with data: $add(), .push(), and .set()

Utilizing Firebase and AngularFire has opened up many different approaches for CRUD operations with the Firebase API. However, I am still uncertain about the specific differences between using: $add with $firebaseArray The .push() method The .set() metho ...

The format of the date cannot be modified when using DesktopDatePicker as a React Component

I've been attempting to modify the appearance of the component, but the UI keeps showing the date in month-year format. <DesktopDatePicker inputVariant="outlined" label="Pick-up date" id="date ...

Determining the nearest upcoming date from a JSON dataset

Looking to find the nearest date to today from the array "dates". For example, if today is 2011-09-10 -> the next closest date from the JSON file is "2012-12-20" -> $('div').append('date1: ' + dates.date1); For example 2, if today is ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

Unable to access res.name due to subscription in Angular

Right now, I am following a tutorial on YouTube that covers authentication with Angular. However, I have hit a roadblock: The code provided in the tutorial is not working for me because of the use of subscribe(), which is resulting in the following messag ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

You are limited to storing only up to 2 items in the localStorage

My goal is to save items in local storage as an array of objects. Initially, it works perfectly and stores the first element in local storage as needed. However, I am facing an issue where I cannot store more than one element. Below is the code block that ...

How can I use conditional 'if' statements to import separate modules in Node.js ES Modules?

Recently, I tried out a tutorial that utilises CommonJS for exporting/ importing different keys depending on the environment. However, I am wondering how I can make it compatible with ES Modules import/export instead? This is the code snippet provided in ...

Reloading the React/Laravel application causes the app to crash and display a blank page

My current setup involves a react application running on the Laravel 5.4 framework. The problem I'm facing is that whenever I refresh a page with a URL structure like {url}/{slug}, it causes issues within the application. Within my App.js file, here ...

What is the best way to eliminate the nesting in this ternary operation?

Object.values(filter).filter(item => (Array.isArray(item) && item.length > 0) || (typeof item === "boolean" && item === true) || (item !== null)).length ? filterIcon : unFilledIcon In this code, I aim to simplify the nested ternary operator and ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Can qTip 2.0 be configured to use a different default attribute instead of 'title'?

Is there a way to set qTip to use an attribute other than 'title' as the default? I need to use another attribute because when I disable qtip and add elements dynamically with "title", the title still shows when I hover over the element, which i ...