Arrange a List in immutable.js by using an array of index values

My scenario involves working with an Immutable list to populate a drag and drop feature. The list items do not have any ids, only indices when mapped through.

const list = Immutable.List([{"alias":"cat"},{"alias":"dog"},{"alias":"rat"}])

Upon dragEnd, I receive an array representing the new order of the list, but it lacks any specific identifiers for the list items apart from the previous order's indices.

const newOrder = [{"order":1},{"order":0},{"order":2}]

I am faced with the task of dispatching a re-ordered Immutable data list based on these indices to update my store. So far, I haven't found a concise and efficient way to achieve this. My initial thoughts were to use sortBy or create an orderedMap from the original list, referencing it using the newOrder array to generate the orderedList. However, none of these approaches seem to be working effectively.

The desired dispatched result is:

const orderedList = Immutable.List([{"alias":"dog"},{"alias":"cat"},{"alias":"rat"}])

What would be the most optimal solution in this case?

Answer №1

If you want to rearrange an array according to a specific order, you can utilize the map function:

const newOrder = [{"order":1},{"order":0},{"order":2}];

const ordered = 
Immutable.List([1,2,3])
  .map(
    (item,index,all)=>
      all.get(newOrder[index].order)
    );

console.log(
  JSON.stringify(
    ordered.toArray(),
    undefined,
    2
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>

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

The element fails to receive the class when it is being clicked

Currently, I am in the process of developing a Joomla website and I am working on implementing an accordion feature for the category descriptions based on the placement of H3 headings in the WYSIWYG editor. Here is the basic function I have so far (althou ...

Solving the puzzle of complex polymorphic object model deserialization in Java Jackson: Facing the JsonMappingException error – Unexpected token (START_OBJECT) instead

I am working with a hierarchy of objects described as follows: A B extends A C extends B D extends B E extends C F extends A and contains a reference to A The annotation for class A is defined as: @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=Jso ...

What is the best way to ensure that this <span> maintains a consistent width, no matter what content is placed inside

So here's the deal, I've got some dynamically generated html going on where I'm assigning 1-6 scaled svgs as children of a . The span is inline with 2 other spans to give it that nice layout: https://i.sstatic.net/mySYe.png I want these "b ...

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 ...

Tips for creating/reading a file in an Android app that contains an array

I am currently working on two activities called EnterPin and ConfirmPin. Each activity has its own array, pin and confirmpin respectively. My goal is to compare the two arrays by using a file where Enterpin would write to the file and Confirmpin would read ...

Field for Entering Time

I need help creating a form that will only accept time values formatted as HH:MM. Can someone guide me on how to filter user input and display the colon in the text field? I am thinking that I might need a specialized input box for this purpose. ...

Numerous classifications and tags available for c3-angular-directive-c3 charts

I have a project requirement to create a stacked bar chart that should look like the image below: https://i.sstatic.net/MBwXy.png Currently, I am utilizing the c3-angular-directive library along with c3.js for chart creation. The challenge lies in dealin ...

Encountering Issues with Installing Postgres Module in Node.js along with FAQs about Node.js

I've encountered a problem while trying to install the Postgres database module for Node.js. Whenever I execute the command "npm install pg", I receive the following error message: C:\>npm install pg<br> npm http GET https://registry.n ...

Extracting data from an HTML image in Django: A step-by-step guide

I am facing a challenge of adding links to multiple images generated in HTML from local folders. These links should be triggered by a view function called create_pc, which will also receive the image path as a parameter. Here is a snippet from my HTML fil ...

Mastering React children: A guide to correctly defining TypeScript types

I'm having trouble defining the children prop in TypeScript for a small React Component where the child is a function. class ClickOutside extends React.PureComponent<Props, {}> { render() { const { children } = this.props; return chi ...

Utilize Javascript to conceal images

On a regular basis, I utilize these flashcards. Recently, I have started using images as answers. However, I am facing an issue - I am unable to conceal the pictures. My preference is for the images to be hidden when the webpage loads. function myShowTe ...

There appears to be a few bugs present in my html code

I'm uncertain about what I am missing, can someone help me out? Thank you. When I click "check," it returns wrong(); It should actually return yes(); because both have the same value and result. However, it's only giving wrong(); If the value ...

Is there a way to utilize OpenLayers to showcase various icons for distinct features all within one layer?

Being new to Openlayers/JS and fairly inexperienced with programming in general, there may be other issues in my code that I'm unaware of. I am currently using the latest version of Openlayers (5.3.0). My application sends GeoJson formatted data via ...

Update a variable globally within setInterval function

Seeking assistance on showcasing the number of seconds that have elapsed using a setInterval function in JavaScript integrated within HTML. The code snippet below has been attempted, but it is only displaying 1 second and the test function appears to not ...

Is there a way in AngularJS utilizing ui-router to retrieve the ngResource error from $stateChangeError when a request fails in the resolve section of a state?

Check out this plunker where I am facing an issue: http://plnkr.co/edit/vdctsTcMq4nD1xpUl3pu The problem is that the $resource promise is being rejected due to a request failure (404 error). I am aware that I can handle the error within the resolve block ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Exploring the possibilities of implementing Undo and Redo features in freehand drawing with Reactjs on

After attempting to create a Freehand drawing using HTML5 canvas with React, my next step is to incorporate an undo and redo functionality when the corresponding buttons are clicked. I would greatly appreciate any assistance provided. function App(props) ...

"Step-by-step guide for incorporating a mask in the Ant Design Datepicker component in React

Could someone help me figure out how to add a mask in the antd datepicker and validate it to ensure the correct date format (dd/mm/yy)? Here is the code I have attempted: <FormItem label="Date of Birth"> {getFieldDecorator("dob", {rules: [{ require ...

Create an onClick function that can direct you to a specific hyperlink without triggering a new browser window to open

Material UI is being used and a home icon has been imported into the navbar as shown below <Home edge="start" color="inherit" aria-label="home" onClick={event => window.location.href='/ <Home fontSize="lar ...

It appears that the mysqli_query function is executing more than once

One of the features on my website involves displaying different URLs inside an iframe. To ensure that each URL is only shown once to the user, I have implemented a custom function. The process involves creating arrays of available URLs and previously seen ...