I desire to rearrange the items within several arrays of lists

I currently have an array set up like this

0: (5) ["2", "X", "8", "11", "15"] 
1: (5) ["1", "5", "X", "X", "14"]
2: (5) ["X", "4", "7", "10", "13"]
3: (5) ["X", "3", "6", "9", "12"]

My goal is to swap the position of the digit 1 with the position of digit 2 in order to get this desired outcome:

0: (5) ["1", "X", "8", "11", "15"]
1: (5) ["2", "5", "X", "X", "14"]
2: (5) ["X", "4", "7", "10", "13"]
3: (5) ["X", "3", "6", "9", "12"]

This array is returned all at once, so I need a way to rearrange the elements after it's returned.

Currently, I am working with JavaScript. Thank you in advance for any help or suggestions.

I attempted to use the following code snippet:

Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};

However, this code ends up moving entire rows together, rather than just swapping individual digits within the arrays.

Answer №1

Identify the outer array index and inner array index for both elements, then perform a swap:

const input = [
 ["2", "X", "8", "11", "15"] ,
 ["1", "5", "X", "X", "14"],
 ["X", "4", "7", "10", "13"],
 ["X", "3", "6", "9", "12"]
];

const getLoc = char => {
  const arrIndex = input.findIndex(subarr => subarr.includes(char));
  const subArrIndex = input[arrIndex].indexOf(char);
  return [arrIndex, subArrIndex];
};
const move = (char1, char2) => {
  const [loc1, loc2] = [char1, char2].map(getLoc);
  
  [
    // switch position of first character:
    input[loc1[0]][loc1[1]],
    // and position of second character:
    input[loc2[0]][loc2[1]]
  ] = [
    // with position of second character:
    input[loc2[0]][loc2[1]],
    // and the first character:
    input[loc1[0]][loc1[1]]
  ];
};

move('2', '1');
console.log(input);

Answer №2

If you want to find the first index of "2" and "1" in their respective arrays using findIndex, you can do so and then replace them. Alternatively, if you only need to replace an element at a specific index, you can directly target that index within the array.

let data = [
  ["2", "X", "8", "11", "15"],
  ["1", "5", "X", "X", "14"]
];


let find2In1 = data[0].findIndex(item => item === "2");
let find1In2 = data[1].findIndex(item => item === "1");
data[0][find2In1] = "1";
data[1][find1In2] = "2";

console.log(data)

Answer №3

Based on the provided sample, it seems like you should switch between 1 and 2.

Example

0: (5) ["2", "X", "8", "11", "15"] 
1: (5) ["1", "5", "X", "X", "14"]
2: (5) ["X", "4", "7", "10", "13"]
3: (5) ["X", "3", "6", "9", "12"]

Modified Output

0:(5) ["1", "X", "8", "11", "15"]
1: (5) ["2", "5", "X", "X", "14"]
2: (5) ["X", "4", "7", "10", "13"]
3: (5) ["X", "3", "6", "9", "12"]

You can achieve this by iterating through each array using forEach method.

a.forEach((item) => {

   if (item === "1")
      item = "2"
   else
      if (item === "2")
          item = "1"
})

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

A guide to filtering out items from observables during processing with RxJS and a time-based timer

I have a complex calculation that involves fetching information from an HTTP endpoint and combining it with input data. The result of this calculation is important for my application and needs to be stored in a variable. async calculation(input: MyInputTy ...

At times, JavaScript interacts with Selenium to click on the login button before I have the chance

I have a challenge while attempting to log in to Twitter using Selenium webdriver, here is the code I am working with: const {Builder, By} = require("selenium-webdriver"); (async function example() { let driver = await new Builder().forBrowser(' ...

The importance of using a reviver function in JSON.parse for handling nested

I am working on customizing the JSON.parse function by using the optional reviver argument to specify that I want the calc(string) function to focus on a key named "expr" within the input string. Once that key is processed, the function should then operate ...

Is it possible to disable other options when a checkbox is checked, but enable them all when unchecked using

I am trying to create a group of checkbox buttons where if one is checked, the others should be disabled. When the checked checkbox is unchecked, all checkboxes should be enabled. However, my current code is experiencing issues where all checkboxes become ...

Developing with Phonegap Build: A Guided Process

With all the conflicting information available, I am seeking clarity on this topic. Objective: To create and enhance a Phonegap app using Phonegap Build. 1) My preference is to utilize Phonegap Build without needing to install Android and iOS SDKs. 2) I ...

PHP arrays can be easily extended by appending additional elements

Having three arrays representing category IDs in Wordpress, each with the format $base_cat_id['term_id'], I aim to assign a post to all three categories using the function below: wp_set_post_categories($entry['post_id'], $base_cat_id + ...

Ascending with Progress Indicator Slider

After successfully creating a Bootstrap 5 Carousel with an automated count for each slide (limited to 4) and a corresponding progress bar, I encountered an issue with getting the previous button to function correctly. While clicking the next button works s ...

Verify the checkbox for validation is shown exclusively

I am currently facing an issue with a form that includes a checkbox, which is only displayed under certain conditions. I want to ensure that the checkbox is checked only when it is visible, and if not, the form should be submitted upon clicking the submit ...

Modify the displayed text according to the content of the input field in HTML

I need to update the value of an <h3> tag based on user input in an input field. Here is my current code snippet: <input id="Medication" name="Medication" size="50" type="text" value=""> <script> $(document).ready(function () { $(&apos ...

When invoking `render(@partial)` in the controller, an error is thrown: ActionController::Unknown

When trying to render a partial using ajax, I encountered an error that reads as follows: ActionController::UnknownFormat in ThingsController#upvoterandom ActionController::UnknownFormat This error is baffling because I previously achieved a similar task ...

I keep encountering the error message "SyntaxError: Cannot use import statement outside a module" even after including "type": "module" in the package.json file. How frustrating to still be faced with yet another error

Upon running the code snippet provided, an error message is displayed stating "SyntaxError: Cannot use import statement outside a module." Despite successfully installing node-fetch using npm install node-fetch What could be causing this issue? import fet ...

Having trouble getting the CSS animation to work properly with the text

Update: The direct link is working fine, unlike the rocketscript version. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> I have been attempting to animate word rotati ...

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

Using jQuery to extract a href URL from a div tag with jQuery

Is it possible to extract the href urls from anchor tags within a div tag? <div id="testing"> <a onclick="http://google.com">google</a> <a href="http://facebook.com">facebook</a> <a onclick="http://gmail.com">gmail< ...

Easy Ways to Retrieve the Current Date and Time

Is there a way to retrieve the current date and time using angularjs I attempted the following method: <b>{{Date.Now}}</b> Unfortunately, this approach did not yield the desired results. Any tips or suggestions would be highly valued. ...

Prevent selection of weekend dates in Angular Bootstrap datepicker with a personalized directive

I have integrated the Angular Bootstrap datepicker plugin into my Angular application. To customize the date pickers in my app, I created a custom directive. In certain places, I need to disable weekends in the date picker. I have added the functions to d ...

Verifying the visibility of a div and triggering its closure upon clicking outside of it

Would anyone be able to provide guidance on how I can merge these two scripts into one? Thank you in advance! $(document).ready(function(){ if ($('.myContainer').is(':visible')) { alert('Hello'); } }); $(doc ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...

ngOptions not updating the selected item in the select dropdown

My Angular code is not reflecting the selected option in the select input. Even though I have specified Hospital One to be selected, it's not happening. Can anyone figure out what might be causing this issue? I've also shared the same code snipp ...

Add an element to an array at a designated position using a pipeline operation (aggregation or update) in MongoDB

After coming across another inquiry, I delved into the search for a standard method to add an element at a specific location within an array using a pipeline, but my quest turned up empty. Suppose my document structure resembles the following: [ { _i ...