Arranging objects in an array based on a separate array of strings

Here is an array of objects that I need to rearrange:

var items = [
  { key: 'address', value: '1234 Boxwood Lane' },
  { key: 'nameAndTitle', value: 'Jane Doe, Manager' },
  { key: 'contactEmail', value: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bf5f0f7f1fcf2f6ebf7dffaf0fcf4f1b3fef2f0">[email protected]</a>' },
  { key: 'contactPhone', value: '9876543210' },
  { key: 'localPhone', value: '9876543210' },
  { key: 'status', value: 'pending' },
]

I have another array called order with the desired order for these objects:

var order = [
  'nameAndTitle',
  'contactPhone',
  'contactEmail',
  'address',
]

I need to arrange the items array according to the order specified in the order array. Any ideas on how to achieve this?

Answer №1

To organize the indices, consider sorting them by their differences.

var objs = [{ key: 'address', value: '1234 street' }, { key: 'nameAndTitle', value: 'John Smith, CEO' }, { key: 'contactEmail', value: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae0e5e2e4f9e7e3fee2caede7ebe3e6a4e9e5e7">[email protected]</a>' }, { key: 'contactPhone', value: '1234567890' }],
    keys = ['nameAndTitle', 'contactPhone', 'contactEmail', 'address'];

objs.sort((a, b) => keys.indexOf(a.key) - keys.indexOf(b.key));

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

To have full control over the sequence, utilize an object with preset order values and include a default property with a lower value than others to sort unknown keys at the start or with a higher value for the end of the array.

This method also suits complex sorting criteria where unlisted items can be sorted in the middle if required.

var objs = [{ key: 'localPhone', value: '1234567890' }, { key: 'status', value: 'open' }, { key: 'address', value: '1234 street' }, { key: 'nameAndTitle', value: 'John Smith, CEO' }, { key: 'contactEmail', value: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b414443455846425f436b4c464a424705484446">[email protected]</a>' }, { key: 'contactPhone', value: '1234567890' }],
    order = { nameAndTitle: 1, contactPhone: 2, contactEmail: 3, address: 4, default: Infinity };

objs.sort(({ key: a }, { key: b }) => (order[a] || order.default) - (order[b] || order.default));

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

ES5

var objs = [{ key: 'localPhone', value: '1234567890' }, { key: 'status', value: 'open' }, { key: 'address', value: '1234 street' }, { key: 'nameAndTitle', value: 'John Smith, CEO' }, { key: 'contactEmail', value: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8a2a7a0a6bba5a1bca088afa5a9a1a4e6aba7a5">[email protected]</a>' }, { key: 'contactPhone', value: '1234567890' }],
    order = { nameAndTitle: 1, contactPhone: 2, contactEmail: 3, address: 4, default: Infinity };

objs.sort(function (a, b) {
   return (order[a.key] || order.default) - (order[b.key] || order.default);
});

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

Answer №2

To maintain the integrity of your original array, you have the option to create a new array by pushing the objects in the desired order.

However, if altering the original array is not a concern, you can simply utilize the sort function which will arrange the keys based on their position in the 'keys' array (there are resources available to assist you with this method).

edit @Nina Scholz quickly implemented the solution ^^

const objs = [{
    key: 'address',
    value: '1234 street'
  },
  {
    key: 'nameAndTitle',
    value: 'John Smith, CEO'
  },
  {
    key: 'contactEmail',
    value: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e040106001d03071a062e09030f0702400d0103">[email protected]</a>'
  },
  {
    key: 'contactPhone',
    value: '1234567890'
  },
];

const keys = [
  'nameAndTitle',
  'contactPhone',
  'contactEmail',
  'address',
];

const array = keys.reduce((tmp, x) => {
  const item = objs.find(y => y.key === x);

  if (item) {
    tmp.push(item);
  }

  return tmp;
}, []);

console.log(array);

Answer №3

To rearrange the array, you can utilize the sort method like this:

var items = [{
    category: 'fruit',
    name: 'apple'
  },
  {
    category: 'vegetable',
    name: 'carrot'
  },
  {
    category: 'fruit',
    name: 'banana'
  },
  {
    category: 'vegetable',
    name: 'lettuce'
  }
]

var categories = [
  'vegetable',
  'fruit',
]

items.sort(function(a, b) {
  return categories.indexOf(a.category) - categories.indexOf(b.category);
});

console.log(items)

Answer №4

One way to achieve this is by following these steps:

Iterate through a string array and compare the value (nameAndTitle) with the corresponding index value in your object array. If there is no match, locate that string within the key-tag in your object array and relocate it to the correct index position. This approach should help you accomplish the task effectively.

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

Issues arise when jQuery functions do not execute as expected within an "if" statement following

Recently, I delved into the realm of AJAX and embarked on a journey to learn its intricacies. Prior to seeking assistance here, I diligently scoured through past queries, such as this, but to no avail. Here is an excerpt from my code: $('.del'). ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Managing the URLs of single page applications

Typically in a Single Page App (SPA), there is usually one main page that contains a side navigation menu with various anchor tags. These anchor tag URLs are managed by the angular/react/sammy js router, and the content of the main section is updated based ...

Set my click event handler back to its default setting

I'm struggling with resetting a click function after it completes. How can I make sure it's ready to run again? $('body').on('click', '#ConfirmBet', function () { function randomImg() { var imgs = $(&apo ...

Dispatch prop within useEffect

App.js -> <Lobbies inGame={inGame} setLobby={setLobby} userName={userName} userKey={userKey}/> Lobbies.js -> import React, { useState, useEffect } from 'react'; import firebase from 'firebase'; const Lobby = ({userKey, ...

Translation of country codes into the complete names of countries

Currently, my code is utilizing the ipinfo.io library to retrieve the user's country information successfully. This is the snippet of code I am using to fetch the data: $.get("https://ipinfo.io?token=0000000000", function(response) { console.log ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

Ways to obtain every image placed onto an element

Using the img tag within div.image-block sets a background. Images can be added to .block3 through drag and drop. Is there a way to create a container that includes all elements from .image-block? <style> .image-block { position: relat ...

There seems to be a problem with the external JavaScript file not functioning

After dragging and dropping the .js file into my ASP.NET project, I am facing an issue where it remains unresponsive, even though the code works fine when used inline. This problem is occurring while using VS 2017. Here is a snippet of my code: <scrip ...

React-highlightjs failing to highlight syntax code properly

I'm currently using the react-highlight library to highlight code snippets in my next.js application. However, I've encountered an issue with the code highlighting when using the a11y-dark theme. https://i.stack.imgur.com/ip6Ia.png Upon visitin ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

Dimming the background of my page as the Loader makes its grand entrance

Currently, I am in the process of developing a filtering system for my content. The setup involves displaying a loader in the center of the screen whenever a filter option is clicked, followed by sorting and displaying the results using JQuery. I have a v ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

how to set a variable's value outside of a Promise using internal code

export class YoutubeService { getTrendingVideos(country) { let result = []; return axios.get('/').then(function(res){ result = res.data.items; for (var i = 0; i < result.length; i++) { result[i] = { id: ...

Retrieve the numerical key within an md-directive

How can I access a Json object with a numerical key in an ng directive? Take a look at the object below: { 0 : { value : { firstname : "John" , lastname : "Doe" } } I want to retrieve the first name of this object using a md directive like: <th md-c ...

Encountering an issue while attempting to retrieve information from Vuex store

I recently encountered an issue while trying to store my water data in Vuex. I followed the implementation below, but when I attempted to access my data array, it did not show up as expected. const store = new Vuex.Store({ state: { categories: ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...