Shuffle Array of Objects in JavaScript Based on Specific Property

Suppose I have a JavaScript array that looks like this:

arrTest = [
  {qId: 1, text:"test a", order: 1},
  {qID: 2, text:"test b", order: 2},
  {qID: 3, text:"test c", order: 3},
  {qID: 4, text:"test d", order: 4}
];

My goal is to randomize only the values in the 'order' key while keeping all other keys unchanged and preserving the original order of the array:

arrTest = [
  {qId: 1, text:"test a", order: 3},
  {qID: 2, text:"test b", order: 1},
  {qID: 3, text:"test c", order: 4},
  {qID: 4, text:"test d", order: 2}
];

I've come across various discussions and functions for randomizing arrays, but none seem to specifically target a single key while leaving everything else intact.

If you have any advice or solutions, it would be greatly appreciated!

Thank you in advance!

Answer №1

If you're looking to shuffle the order of elements in an array and assign random values back to the property, one approach could be to map the 'order' property and then randomly assign a value from that mapping.

var arrTest = [{ qId: 1, text:"test a", order: 1 }, { qID: 2, text:"test b", order: 2 }, { qID: 3, text:"test c", order: 3 }, { qID: 4, text:"test d", order: 4 }],
    random = arrTest.map(({ order }) => order);
    
arrTest.forEach(o => o.order = random.splice(Math.floor(Math.random() * random.length), 1)[0]);

console.log(arrTest);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Utilize the Array.map() method to extract the order, then shuffle the order array using a technique from this solution, and finally use Array.map() to apply the new order to the original array:

const arrTest = [{"qId":1,"text":"test a","order":1},{"qID":2,"text":"test b","order":2},{"qID":3,"text":"test c","order":3},{"qID":4,"text":"test d","order":4}];

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
      let j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
  }
  
  return array;
}

const result = shuffle(arrTest.map((o) => o.order))
  .map((order, i) => ({
    ...arrTest[i],
    order
  }));
  
console.log(result);

Answer №3

When faced with a similar challenge, I often turn to the robust capabilities of the lodash library (https://lodash.com/docs). This versatile tool offers a wide range of functions that I find invaluable in my JavaScript projects. Below is an example of how I utilized lodash for this specific task:

_(arrTest)
   .map(element => element.order)
   .shuffle()
   .each( (order, index) => arrTest[index].order = order);

console.log(arrTest);

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

How can I transfer data from an API response containing an array of objects to a new array in a Vue.js

How come I am getting NaN instead of "qwe" and "qweqweqwe" when trying to push the first 6 elements from an array of objects to a new array? Imagine the array of objects retrieved from the API is structured like this: 0: {id: 340, name: "qwe", lastname: ...

What is the most effective approach for integrating an edit feature into my React component?

For a while now, I've been working on a Reviews react app and have encountered an issue. Each Review can have only one ReviewResponse, but I need to implement functionality for editing the response. Currently, the response form is hidden once a review ...

When the text overflows from the div, place it on a new line to ensure readability

I have been struggling to make my text wrap onto a new line within the box. You can view the JS Fiddle Demo here: http://jsfiddle.net/SfG8r/1/ Essentially, I want the text to wrap onto a new line like a paragraph in a book when it exceeds the box boundari ...

What is the best way to use JavaScript to locate and interact with a button on a webpage based on its XPath and the text it contains?

Is it possible to find a specific element by the text it contains using only JavaScript? While in Selenium we can easily locate elements based on their text content, for instance: the_element = browser.find_element_by_xpath("//span[contains(.,TEXT)]") In ...

The default ng-selected option fails to show up in the form POST without any modification

Within a select list, I have set one option to be selected by default using ng-selected. However, when submitting the form with the default option selected through the post method, it does not show up in the post variables. Interestingly, if I change the ...

The D3 path is generating an unexpected output of 0px by 0px, causing the map not to display properly. I am currently unsure how to adjust the projection to

I am currently working on creating a world map using D3. I obtained the JSON file from the following link: https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json Below is the code snippet I'm using: // Defining SVG dimensio ...

Ways to conceal the current state changes from being displayed in the URL

I've implemented a React form with text fields and radio buttons to store data in the state. The 'Proceed' button triggers an onClick function: handleClick(event){ console.log(this.state); var userID = 1; firebase.database().ref ...

Trouble with sending data from jQuery Ajax to Node.js server

I am in the process of developing a video streaming platform that needs to constantly update the backend on the status of the videos being played. However, I am encountering an issue where the data sent through an ajax request appears as an empty object {} ...

Saving the AJAX response object in a global variable - Important fields are not being retrieved

Currently, I am developing an asynchronous webpage in Grails wherein I invoke a controller and display the response as a D3.js network. To ensure further usability, I saved the object as a global variable. Despite the successful execution of the function u ...

How do I set up Firebase functions to trigger onWrite when listening for a specific child just once?

Is there a way to access the child under a different node each time the Firebase onWrite function is triggered? To retrieve this child, you can use the following code: {const saatt = (context.database.ref('kullanicilar/1111/marina1/2021/1saat'). ...

Learn how to serialize and submit all form components within a specified element using AJAX

I am attempting to serialize and post all form elements that may originate from either within a <form> element, or any other elements such as divs, trs, etc. In essence, my form can be structured in two ways: <form id="frm1"> Name: ...

What is the process for advancing an object in Three.js?

Does anyone know how to advance the position of an object in Three.js? I've been thinking about converting rotation.x, y, z into a vector and manipulating it that way. However, as a beginner, I'm unsure of how to proceed. Any guidance would be g ...

Tips for maintaining constant variables during React rendering

Having trouble with React issues. I've developed a front-end online shop using React const products = [ { id: 1, name: "Oppo", price: 200, unit: 1, img: "oppo.jpg" }, { id: 2, name: "Samsung", price: 250, unit: 1, img ...

The parameter cannot be assigned because it is of type 'string | Date', not of type 'Date'

As I attempt to create a test suite with date mocking, I encounter an error stating 'Argument of type 'string | Date' is not assignable to parameter of type 'Date''. Below is the function: const getDay = (inputDate: any, today ...

Evolution of table size

I have a table that needs to expand smoothly when a certain row is clicked. I want to add a transition effect for a more polished look. Here's my test table: <div ng-app="app"> <table> <thead ng-controller="TestController" ...

Troubleshooting a Tiny Bottom Sheet Problem in react-native

On my page, I have a bottom sheet that takes up 3/4 of the space. Then, within that bottom sheet, I open another bottom sheet that only occupies 1/4 of the space (without closing the first one). ...

What is the process for extracting a .swf file from the Rails Asset Pipeline without using any helper methods?

Currently, I am developing a Rails/React application without utilizing the react-rails gem. The project is organized into separate directories for front-end and back-end code. My current task involves creating a cross-browser solution for embedding webcam ...

What is the best way to relocate a child component to a different parent in React?

I have a list of child components with checkboxes, and when a checkbox is clicked, I want to move that child component inside another div. Below is an illustration of how my app should look. I need to select student names and shift them up under the "Pres ...

Could you offer assistance in resolving the error I am encountering with the collection.get() function?

I encountered an issue while trying to implement a database in my project. I imported 'collection' to use in my code. Here is the snippet: import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js"; import ...

Exploring the nuances of shimming dependencies with requireJS: comparing shorthand to longhand notation

I'm currently using the following shim configuration with RequireJS: shim: { 'thirdParty/jquery.jqGrid': ['jquery', 'jquery-ui', 'thirdParty/grid.locale-en'] } I'm curious to know if this is exactly t ...