Arranging object array according to a reference array in Javascript

My task involves sorting the properties of objects in an array based on the sequence of another array.

let arrToSort = [
   { Architect: 'Terry', Client: 'AZ', ClientType: 'Kids', Location: 'USA'},
   { Architect: 'Mary', Client: 'XY', ClientType: 'Clothes', Location: 'Germany'},
   { Architect: 'Jerry', Client: 'BC', ClientType: 'Construction', Location: 'Canada'}
];

let accordingTo = ["ClientType", "Architect", "Location", "Client"];

The desired output is as follows:

finalArr = [
   { ClientType: 'Kids', Architect: 'Terry', Location: 'USA', Client: 'AZ'},
   { ClientType: 'Clothes', Architect: 'Mary', Location: 'Germany', Client: 'XY'},
   { ClientType: 'Construction', Architect: 'Jerry', Location: 'Canada', Client: 'BC'}
]

Answer №1

let arrayToSort = [{ Architect: 'Terry', Client: 'AZ', ClientType: 'Kids', Location: 'USA' }, { Architect: 'Mary', Client: 'XY', ClientType: 'Clothes', Location: 'Germany' }, { Architect: 'Jerry', Client: 'BC', ClientType: 'Construction', Location: 'Canada' }];
let orderBy = ["ClientType", "Architect", "Location", "Client"];

let sortedArray = arrayToSort.map(item => Object.keys(item).sort((x, y) => orderBy.indexOf(x) - orderBy.indexOf(y)).reduce((result, key) => {
  result[key] = item[key]
  return result
}, {}))

console.log(sortedArray)

Answer №2

Map objects maintain the order of keys, unlike regular objects where keys are not ordered. Therefore, when iterating over a Map object, keys are returned in the order they were inserted. (It is worth noting that according to the ECMAScript 2015 specification, objects do preserve creation order for string and Symbol keys, so traversing an object with only string keys would yield keys in the order of insertion.)

let arrToSort = [{
    Architect: 'Terry',
    Client: 'AZ',
    ClientType: 'Kids',
    Location: 'USA'
  },
  {
    Architect: 'Mary',
    Client: 'XY',
    ClientType: 'Clothes',
    Location: 'Germany'
  },
  {
    Architect: 'Jerry',
    Client: 'BC',
    ClientType: 'Construction',
    Location: 'Canada'
  }
];
let accordingTo = ["ClientType", "Architect", "Location", "Client"];

function sortByKeys(arr, keyOrder) {
  let newArray = [];
  arr.map((obj) => {
    const newObj = {};
    keyOrder.forEach((key) => {
      newObj[key] = obj[key];
    })
    newArray.push(newObj)
    return obj;
  });
  return newArray;
}
arrToSort = sortByKeys(arrToSort, accordingTo);

console.log(arrToSort);

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

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Tips for executing a series of tasks before a node js process is terminated

Dealing with signal from an external file in a JavaScript file. I have a shell script that stops all running processes. When my node process is stopped or killed, I need to perform a specific task before allowing the node to stop/killed. In my JavaScript ...

Why does Vue only change a specific array element without updating the DOM?

My curiosity is piqued by a puzzling issue with updating specific items in an array using Vue.js. The documentation cautions that: Due to limitations in JavaScript, Vue cannot detect the following changes to an array: When you directly set an item with th ...

Always make sure to call for files using their respective names in

Here is how my project structure looks like: . ├── node_modules ├── package.json ├── www │ ├── css │ ├── js │ ├── file.js │ ├── folder │ ├── file2.js │ ├─ ...

AngularJS Filter without creating a new object

Within my code, I am dealing with an array of objects that contain sub-objects. This particular array is utilized in an ng-repeat to display data in a table format. To illustrate, consider the following example: device { "name": "computer" ...

Comparing Redux with passing state down to components as props from the top level of the application

With limited experience in react-redux, I am currently working on a smaller web-based application intended for around 100 users. At this time, I have opted not to use redux due to concerns about its complexity for such a small project. Instead, I have been ...

Obtain the visual representation of an object created in three.js during the rendering process

I have been pondering the way in which three.js handles rendering. It seems to me that it converts each element into an image before drawing it on a context. I'm curious if there are resources available where I can learn more about this process. Addit ...

Command is not displaying JavaScript

Having difficulty grasping the task at hand. As a Mac user, my goal is to construct a 3D portfolio but I'm facing challenges. The issue lies in JavaScript not appearing on Variants. Upon entering "npm init vite.js/app," a framework is generated, follo ...

Displaying JavaScript array contents in an HTML page without using the .innerHTML property

As someone new to the world of JavaScript and web development, I find myself faced with a challenge. I want to showcase the contents of two different JavaScript arrays in an HTML format. However, my research has led me to believe that utilizing .innerHTML ...

The complexity of reading code increases when ajax requests are nested

I often prefer to structure my code in a way that one function triggers multiple other functions, like the example below: /** * GET MESSAGES: */ $(function() { $.ajax({ url: '/messages', method: 'GET', dataType: 'j ...

Guide on incorporating a library into your Ionic application without the need to upload it to npm

Recently, I successfully created an Angular application, an Ionic application, and a custom library in my workspace. I am able to import the library files into my Angular application but facing challenges when trying to import them into my Ionic applicat ...

When trying to fetch data from a React front end using axios, the request body's title is coming back

I am facing an issue where I keep receiving 'undefined' when attempting to console.log(req.body.title). Additionally, when I console.log(req.body), I am only seeing an empty {} returned. My setup involves React for the frontend and express for t ...

restrict the maximum character count in regex

The string can consist of a single number or multiple numbers separated by "-", but the total character count must not exceed 6. Examples of valid strings 5 55-33 4444-1 1-4444 666666 Examples of invalid strings -3 6666- 5555-6666 My initial regex / ...

The error message generated by Nuxt.js when encountering an issue with dynamic components is "To resolve this issue, either compile the templates into render functions beforehand or utilize the compiler-in

Encountering an issue in Nuxt.js that states: [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build. found in ---&g ...

What's the best choice for me: useState, useRef, or useMemo?

I am facing a situation where I need to retain the result of a function throughout the lifecycle of a component (this value should remain constant). Take a look at the following example const UniqueIdView = () => { const [uniqueIdState1] = useState ...

Ways to truncate text and include a "Read More" button within a v-for loop

The text in the "card-text" class is being retrieved from a Json file, but it's too long. I want to shorten the text and include a "Read More" button that expands the text when clicked on, but only for the specific card that was clicked. Is there a wa ...

Can you explain the contrast between onsubmit="submitForm();" and onsubmit="return submitForm();"?

Is it possible that the form below is causing double submissions? <form name="myForm" action="demo_form.asp" onsubmit="submitForm();" method="post"> function submitForm(){ document.myForm.submit(); } I've noticed a bug where sometimes two ...

Eliminate unnecessary symbols and uppercase letters from a field

Hey there, I run a classified site and could use some assistance from javascript experts. I've noticed that users tend to post ads using ALL CAPS, like: "HELLO THIS IS MY POST TITLE" or sometimes with special symbols like "* HELLO this is >>> ...

Error: Unsupported bitfield value: ADMINISTRATOR. Please input a valid bitfield flag or number. (discord.js v14)

Recently upgraded to discordjs v14.0.3 and encountered an error that was not present in v13. I have a command handler where I can access the permissions from a command, passed as an array. I loop through each permission and check if the message author has ...

A guide to extracting a Primitive Array from ES6 Promises

Currently, my goal is to load glsl scripts as strings by utilizing the ES6 Promise and Fetch APIs. In my attempt to achieve this, I believed that I had devised an elegant solution for fetching the vertex and fragment shaders and then generating a new progr ...