Sorting elements to the beginning of each nested array

Looking to rearrange the elements in the given nested array, moving the element with the id 'cat_spc_my_special_id' to the top of the list using the keyword 'special'.

There are 4 items currently in the above array, and the goal is to filter and move the specific element to the top of the list in this nested structure.

I attempted the following methods:

Method 1:

let filterKey = 'special';
const shoppingBagNew = shoppingBag?.data?.[0]?.sections.filter(function(x,y){
   return x == filterKey ? -1 : y == filterKey ? 1 : 0;
})

Method 2:

const sections = shoppingBag?.data?.[0]?.sections;
const RedIndex = shoppingBag?.data?.[0]?.sections.findIndex(section => section.id == 'special');
shoppingBag?.data?.[0]?.sections.push(...sections.splice(0, RedIndex));
console.log('shoppingBag after filter',shoppingBag);

Is it possible to manipulate the structure of a nested array like this? Any insights or alternative approaches would be greatly appreciated. Thank you!

Answer №1

.filter() does not arrange an array. You must utilize .sort() instead:

const shoppingBag={"activeContainerId":"955bd18f-6561-44b4-ba8f-7094e4e183b8","amendCartContainers":[],"data":[{"id":"955bd18f-6561-44b4-ba8f-7094e4e183b8","categoryName":"My_Category_Name","categoryId":"cat_spc_my_category","sections":[{"id":"cat_spc_my_id","title":"APPLE","items":[{"id":"a6d89ee2-6832-43e4-85ea-6ec541f06c36","action":"add","title":"Apple iPhone 11","characteristics":["something else"],"promotions":[],"quantity":1,"oneTimePrice":[{"something":"else"}],"recurringPrice":[],"totalOneTimePrice":[{"something":"else"}]}]},{"id":"cat_spc_my_id2","title":"My_Title2","items":[{"id":"0ea7cade-96e0-4e5d-8baf-ace2f7ce123f","action":"add","title":"My Inner title2","characteristics":[],"promotions":[],"quantity":1,"addedBySCRuleEngine":true,"oneTimePrice":[{"something":"else"}],"recurringPrice":[],"totalOneTimePrice":[{"something":"else"}],"totalPriceRecurring":[]}]},{"id":"cat_spc_my_special_id","title":"my_special_title","items":[{"id":"870d3871-6a0c-42f2-b123-9d75a3f3e3ee","action":"add","title":"my inner title3","characteristics":[],"promotions":[{"something":"else"}],"quantity":1,"itemTerm":[{"duration":{"amount":12,"units":"Month"}}],"oneTimePrice":[{"something":"else"}],"recurringPrice":[{"something":"else"}],"totalOneTimePrice":[{"something":"else"}],"totalPriceRecurring":[{"something":"else"}]}]},{"id":"cat_spc_my_id4","title":"my_title4","items":[{"id":"1011730c-d8d2-45ac-8ee2-98f981184a85","action":"add","title":"my_title4","characteristics":[],"promotions":[],"quantity":1,"oneTimePrice":[{"something":"else"}]}]}],"totalPriceOneTime":[{"something":"else"}],"totalPriceRecurring":[{"something":"else"}],"promotions":[],"notes":[],"processContext":"ACQ","visibilityInSection":{"id":"bo_lov_visibilityinsection_section1","name":"Section 1","visibilityOrder":1}}],"applyCouponStatus":null,"promotions":[],"totalPriceOneTime":[{"dutyFreeAmount":{"unit":"price_unit","value":479.68},"taxIncludedAmount":{"unit":"price_unit","value":580.41},"dutyFreeAlteredAmount":{"unit":"price_unit","value":479.68},"taxIncludedAlteredAmount":{"unit":"price_unit","value":580.41},"taxAmount":100.73,"amountPayable":{"unit":"price_unit","value":580.41}}],"totalPriceRecurring":[{"dutyFreeAmount":{"unit":"price_unit","value":41.32},"taxIncludedAmount":{"unit":"price_unit","value":50},"dutyFreeAlteredAmount":{"unit":"price_unit","value":24.79},"taxIncludedAlteredAmount":{"unit":"price_unit","value":30},"taxAmount":5.21,"amountPayable":{"unit":"price_unit","value":30}}]};

shoppingBag.data[0].sections.sort((a,b)=>
  a.id.includes("special")? -1 : b.id.includes("special") ? 1 : a.id.localeCompare(b.id)
);

// list ids of resulting array:
console.log(shoppingBag.data[0].sections.map(({id})=>id))

If you simply wish to relocate the element with "special" in its id to the top, you should substitute a.id.localeCompare(b.id) with 0 in the aforementioned .sort() function. This will maintain the original order.

Additionally, to address your query regarding "nested" arrays: an array remains an array regardless of the type of elements or nesting level. The sort() function operates directly on the array.

By the way, your "TRY 2" method will also function (with minor adjustments):

const shoppingBag={"activeContainerId":"955bd18f-6561-44b4-ba8f-7094e4e183b8","amendCartContainers":[],"data":[{"id":"955bd18f-6561-44b4-ba8f-7094e4e183b8","categoryName":"My_Category_Name","categoryId":"cat_spc_my_category","sections":[{"id":"cat_spc_my_id","title":"APPLE","items":[{"id":"a6d89ee2-6832-43e4-85ea-6ec541f06c36","action":"add","title":"Apple iPhone 11","characteristics":["something else"],"promotions":[],"quantity":1,"oneTimePrice":[{"something":"else"}],"recurringPrice":[],"totalOneTimePrice":[{"something":"else"}]}]},{"id":"cat_spc_my_id2","title":"My_Title2","items":[{"id":"0ea7cade-96e0-4e5d-8baf-ace2f7ce123f","action":"add","title":"My Inner title2","characteristics":[],"promotions":[],"quantity":1,"addedBySCRuleEngine":true,"oneTimePrice":[{"something":"else"}],"recurringPrice":[],"totalOneTimePrice":[{"something":"else"}],"totalPriceRecurring":[]}]},{"id":"cat_spc_my_special_id","title":"my_special_title","items":[{"id":"870d3871-6a0c-42f2-b123-9d75a3f3e3ee","action":"add","title":"my inner title3","characteristics":[],"promotions":[{"something":"else"}],"quantity":1,"itemTerm":[{"duration":{"amount":12,"units":"Month"}}],"oneTimePrice":[{"something":"else"}],"recurringPrice":[{"something":"else"}],"totalOneTimePrice":[{"something":"else"}],"totalPriceRecurring":[{"something":"else"}]}]},{"id":"cat_spc_my_id4","title":"my_title4","items":[{"id":"1011730c-d8d2-45ac-8ee2-98f981184a85","action":"add","title":"my_title4","characteristics":[],"promotions":[],"quantity":1,"oneTimePrice":[{"something":"else"}]}]}],"totalPriceOneTime":[{"something":"else"}],"totalPriceRecurring":[{"something":"else"}],"promotions":[],"notes":[],"processContext":"ACQ","visibilityInSection":{"id":"bo_lov_visibilityinsection_section1","name":"Section 1","visibilityOrder":1}}],"applyCouponStatus":null,"promotions":[],"totalPriceOneTime":[{"dutyFreeAmount":{"unit":"price_unit","value":479.68},"taxIncludedAmount":{"unit":"price_unit","value":580.41},"dutyFreeAlteredAmount":{"unit":"price_unit","value":479.68},"taxIncludedAlteredAmount":{"unit":"price_unit","value":580.41},"taxAmount":100.73,"amountPayable":{"unit":"price_unit","value":580.41}}],"totalPriceRecurring":[{"dutyFreeAmount":{"unit":"price_unit","value":41.32},"taxIncludedAmount":{"unit":"price_unit","value":50},"dutyFreeAlteredAmount":{"unit":"price_unit","value":24.79},"taxIncludedAlteredAmount":{"unit":"price_unit","value":30},"taxAmount":5.21,"amountPayable":{"unit":"price_unit","value":30}}]};

// "TRY 2" of OP:
const sections = shoppingBag.data[0].sections,
      RedIndex = sections.findIndex(section => section.id.includes('special'));
 shoppingBag.data[0].sections.unshift(...sections.splice(RedIndex,1));
 
 // list ids of resulting array:
console.log(shoppingBag.data[0].sections.map(({id})=>id))

Instead of .push() which appends an element at the end of an array, you should utilize .unshift() to add it to the beginning. The .splice() should occur at the position where you identify the "special" case:

shoppingBag.data[0].sections.unshift(...sections.splice(RedIndex,1));

Answer №2

Finally, after dedicating a significant amount of time, I found a solution. I utilized the 'structuredClone' method to create a deep copy of the original object.

const replicatedCart = structuredClone(shoppingBag);
let sortedSections = replicatedCart?.data?.[0]?.sections;
if (sortedSections) {
  sortedSections.sort((a, b) =>
    a.title.includes("RED") && -1
  );
}
console.log('sortedSections after sorting', sortedSections);

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

Unable to include an additional parameter within a JavaScript function

I'm having trouble adding a parameter to the Openpopup() function - every time I try, I get an error. Can someone help me out with this? Thanks in advance. return "<a onclick='return Openpopup()' class='btn btn-info btn-lg clickBtn& ...

Why is it that my website in React crashes when I type rapidly in the TextField component?

Whenever I input text quickly into the TextField in my app, it causes my website to crash and display a blank white screen. Below is the snippet of code causing the problem: TextField Code: <TextField label="Item name" ...

The aesthetic of the material tree design is not being reflected as expected

I am attempting to recreate the material tree example showcased here. This is the desired outcome: https://i.sstatic.net/dnkm2.png However, my result appears like this: https://i.sstatic.net/JXdbo.png Below is the HTML code I am utilizing: <mat-tr ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Reading Useless Information from an Input File

In my C++ program, I am working with reading a file in chunks that contain integers (two per line). To begin, I am using the following code snippet to determine the length of the file: input.seekg(0, input.end); int length = input.tellg(); input.seekg(0, ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

What is the method to retrieve content from a different domain using .load()?

When I try to retrieve data from a different domain using .load() or other jQuery ajax functions, it doesn't seem to work. However, accessing URLs on my own domain works perfectly fine. I've heard about a workaround involving PHP and setting up ...

"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following p ...

Advancement of a grunt chore within a digital platform

After constructing an app with grunt, I am now in the process of developing a web interface using node and angular to interact with this app. One feature I have implemented is a button that triggers a grunt task using childProcess in NodeJS: child_process ...

When Typescript calls the toString method on a Function, it produces unexpected characters like "path_1, (0, promises.writeFile)"

I'm currently attempting to convert a function into a string for transmission to a worker thread for execution. However, when imported code is included, the resulting string contains strange characters. import { HttpStatus } from '@nestjs/common& ...

Javascript Macros for Mastering Excel

My goal is to use Javascript macros to handle excel spreadsheets instead of the standard VBA. I have found a way to run javascript code through VBA, as shown below: 'javascript to execute Dim b As String b = "function meaningOfLife(a,b) {return 42;}" ...

When utilizing JavaScript to input text, I have observed that if I enter text in one text box, any previously entered value is automatically deleted

Currently, I am facing an issue with 3 text boxes in a row that I am populating using JavaScript. The problem arises when I enter text into one field and then move to the second box to input text - the value from the first text box gets removed. Below is ...

AngularJS service failing to deliver promised result

I am in the process of retrieving data from my database using AngularJS. I have created a service to fetch the data and a controller to display it. Check out my code snippet: angular.module('myApp') .factory('panelService', [&apos ...

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...

Exceeding a certain size limit when creating a struct array in C leads to a program

Hello everyone! I have recently started learning C programming (just a week ago) and I want to make sure that I am heading in the right direction. Can someone please guide me to the correct path? Here is the struct I created: #define MAX 64 #define ARRAY ...

Ways to retrieve the state within a mapping array

I am currently facing an issue that I need assistance with: this.state.renderMap.map(function(name, index) { return ( <View style={styles.checkBoxWrapper} key={index}> <CheckBox title={name} value={() => {this.state.nam ...

The scroll function is executed only one time

I'm currently working on implementing a sticky sidebar snippet using jQuery. However, I am facing an issue where the function within .scroll() is only executing once instead of on every scroll event. Can anyone help me identify what I might be doing i ...

Ways to get to the bottom in a React component using a button

I've been struggling to automatically scroll the user to the bottom of the page when they click on a button. Despite my best efforts, I haven't been able to find a solution. Can someone please assist me in achieving this goal? Thank you ...

Creating a unique Voronoi Diagram wrap

I am currently working on the creation of a fantasy-style map that is procedurally generated using the cells of a Voronoi diagram to determine different terrains. While working on the tectonic plate generation, I came to the realization that having wrappi ...

Employ the v-model directive in conjunction with a checkbox in scenarios where v-for is implemented with the properties of an object

When utilizing v-model with a checkbox in conjunction with an array of objects, it functions correctly: new Vue({ el: '#example', data: { names: [ { name: 'jack', checked: true }, { name: 'john', checked ...