What is the best way to rearrange (exchange) elements within an Immutable Map?

Is there a way to rearrange items within an unchangeable list that is part of a Map? Here's an example:

const Map = Immutable.fromJS({
    name:'lolo',
    ids:[3,4,5]
});

I have attempted to use the splice method for swapping, as well as the insert() method provided by Immutable.

For instance, if I want to swap from [3, 4, 5] to [3, 5, 4], my attempt looks like this:

list.set('ids', list.get('ids').splice(2, 0, list.get('ids').splice(1, 1)[0])

What is the most effective way to rearrange elements inside Immutable data structures using Immutable.js? Let me know, please.

Answer №1

To achieve the desired outcome, it is recommended to utilize Map.update() in combination with List.withMutations():

map.update('ids', idsList => idsList.withMutations(function (idsList) {
    let temp = idsList.get(2);
    return idsList.set(2, idsList.get(1)).set(1, temp);
}));

I have adjusted the variable names from list to map as it is more accurate to refer to it as a Map.

For a straightforward sorting process, consider implementing:

map.update('ids', idsList => idsList.sort(function (a, b) {
    // magic
});

Answer №2

Custom Function:

function switchKeys(map, key, index1, index2) {
    return map.update(key, array => array.withMutations(array => {
        let firstValue = array.get(index1);
        let secondValue = array.get(index2);
        return array.set(index2, firstValue).set(index1, secondValue);
    }));
}

Answer №3

Utilizing destructuring assignment can facilitate the swapping of values at distinct indexes within an array

const data = Immutable.fromJS({name:'lolo',ids:[3,4,5]});

[data._root.entries[1][1]._tail.array[1], data._root.entries[1][1]._tail.array[2]] = [
  data._root.entries[1][1]._tail.array[2],
  data._root.entries[1][1]._tail.array[1]
];

console.log(data.get("ids").toArray());

Check out the plnkr http://plnkr.co/edit/ZcEFNIFTnji3xxs7uTCT?p=preview

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

What is the best way to export multiple modules/namespaces with the same name from various files in typescript within index.d.ts?

I am currently in the process of creating a new npm package. I have two TypeScript files, each containing namespaces and modules with the same name 'X'. At the end of each file, I declared the following: export default X; My goal is to import bo ...

What is the best way to set a fixed width for my HTML elements?

I am facing an issue with my user registration form where error messages are causing all elements to become wider when they fail validation. I need help in preventing this widening effect. How can I achieve that? The expansion seems to be triggered by the ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

Nesting maps in JavaScript is a powerful way to transform

I'm in the process of developing a budgeting app using React and JavaScript. At the moment, I have successfully generated a table displaying various costs. Name Budget Used $ Used % Available Food 300 300 100 0 Streaming services 600 600 100 ...

What is the process for converting several files into a base64 string?

I have a component set up like this: <input type="file" multiple @change="toBase64Handler($event)"> <script> data() { return { files: [], } }, methods: { tobase64Handler(event) { // implementation } } </script> I w ...

Incorporating an NPM JavaScript library into Laravel version 8

I've integrated the mobiscroll javascript component library into my new Laravel 8 app by adding the minified css/js files to the public/css and public/js directories. However, I'd like to find a more seamless way to include these components by us ...

The API response indicating success is simply denoted as "Success: True", without any accompanying data

I've set up my application on an express server with a proxy to communicate with the API server. Here's a snippet of my code: HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Encountering an error message in MongoDB, specifically the "BadValue" error, when attempting to utilize the $map aggregate function due to the

My goal is to convert an array of strings into an array of ObjectIds using the map function. The map function will generate an array of ObjectIds that I will use in $match to compare if the _id matches with any of the objectids present in the array using t ...

Audio Playlists and Dynamic Loading with WordPress Shortcode

I'm looking to incorporate the wp_audio_shortcode() function using AJAX, and then customize the style of the audio player. However, I'm facing an issue where the HTML code returned by the AJAX request does not allow me to customize the audio play ...

Having issues with ASP.NET MVC AJAX PartialView not loading Telerik UI components

I am facing an issue with a PartialView that I update using AJAX. The HTML elements load correctly when updating the Div with AJAX, but the Telerik chart is not loading. The datasource in the chart does not call the Action method: .DataSource(ds => ds. ...

Looking to optimize this code? I have three specific tags that require reselection within a given list

for (var i=0; i<vm.tags.length; i++) { if (selectedTags[0]) { if (vm.tags[i].term_id === selectedTags[0].term_id) { vm.tags[i].border1 = true; } } if (selectedTags[1]) { if (vm.tags[i].term_id === selecte ...

How can you create a basic click event for a Google Maps marker?

Can a straightforward action be triggered using jQuery or JavaScript when a user clicks on a Google Maps marker? I am attempting to load content into an external div using AJAX when a user clicks on a marker on the map. The following code snippet could se ...

The website is missing the display of Google Maps

The Google map is not displaying on my website page that uses PHP. I need assistance with this issue. Below is the webpage URL and the source code: <section class="meteor-google-map fullwidth block" style="height: 450px; border: solid transparent; bo ...

Leveraging the power of MKL-optimized numpy.dot() for efficient computation with 3-dimensional

I have been working on optimizing my code for quite some time now, and recently discovered a significant performance decrease when using numpy.dot with arrays containing 3 or more dimensions. For instance, consider this code: def ti(): r = random.rand( ...

Leveraging the csv file functionality in the npm package of d3 version 5

Currently in my react project, I am utilizing d3 for data visualization. After installing the d3 module via npm, I found myself with version 5.9.2 of d3. The challenge arose when attempting to use a csv file within d3. Despite scouring various resources, I ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

Trigger a Jquery sound when an HTML result is found and displayed

I am using a Jqgrid to display a table. Within the "return" column, along with other data, there is a span element like the following: <span class="return" id="ret0>4.25%</span> My webpage contains multiple instances of these spans: < ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Converting an object with a combination of different index types into a string representation

I'm dealing with a unique object structure that behaves similarly to an array, except it contains a mix of index types (numbers and strings). Here's an example: var myObj = []; myObj[0] = 'a'; myObj[1] = 'b'; myObj[2] = &apos ...

The functionality of Jquery datatables seems to be faulty when navigating to the second page

While utilizing the jQuery datatables plugin, I encountered an issue where the event click function only worked on the first page and not on subsequent pages. To address this problem, I discovered a helpful resource at https://datatables.net/faqs/ Q. My ...