JavaScript - rearrange array of objects based on specified property

I am currently designing a select dropdown input element for a webpage and I want to create a specific 'popular' options group that will be displayed at the top of the dropdown menu.

The data structure I am working with is as follows. I am trying to figure out a way to rearrange the items within the people array based on their names.

For instance, I need to reposition the following items:
pogo-stick from toys[2] -> toys[0]
cards from toys[3] to toys[2]

I have a list of popular toys, which includes:

popularToys: [
    "cards", "pogo-stick"
]

My question is, how can I loop through the array of objects and organize them according to the new order specified?

Sample Data:

{
  "toys": [
    {
      "name": "car",
      "price": "10"
    },
    {
      "name": "duck",
      "price": "25"
    },
    {
      "name": "pogo-stick",
      "price": "60"
    },
    {
      "name": "cards",
      "price": "5"
    }
  ]
}

Answer №1

Implement a forEach() loop to locate the index of the toy object and then perform a swap:

var popularToys = [
    "cards", "pogo-stick"
]

var data = {
  "toys": [
    {
      "name": "car",
      "price": "10"
    },
    {
      "name": "duck",
      "price": "25"
    },
    {
      "name": "pogo-stick",
      "price": "60"
    },
    {
      "name": "cards",
      "price": "5"
    }
  ]
};
popularToys.forEach(function(toy, index){
  var toyObjIndex = data.toys.findIndex(x => x.name==toy);
  //swap
  var tempObj = data.toys[toyObjIndex];
  data.toys[toyObjIndex] = data.toys[index];
  data.toys[index] = tempObj;
});

console.log(data);

Answer №2

Breaking down the logic using a mix of map and filter allows for a clearer separation into two methods

Popular() filters the toy items based on the name property matching the names in the popular array

Rest() filters the toy items where the name property does not exist in the popular array

const toys = [
  {
    name: 'car',
    price: '10'
  },
  {
    name: 'exception',
    price: '999999'
  },
  {
    name: 'duck',
    price: '25'
  },
  {
    name: 'pogo-stick',
    price: '60'
  },
  {
    name: 'cards',
    price: '5'
  },
  {
    name: 'another !exception',
    price: '100000'
  },
  {
    name: 'pogo-stick',
    price: 'A MILLION POUNDS'
  },
  {
    name: 'duck',
    price: '100'
  }
]

const popular = [
  'cards', 
  'pogo-stick', 
  'car', 
  'duck'
]

const Popular = () => {
  return [].concat(...popular.map(n => toys.filter(({name}) => name === n)))
}
const Rest = () => toys.filter(({name}) => popular.indexOf(name) === -1)

let ordered = [].concat(...Popular(), ...Rest())

console.log(ordered)

Answer №3

A custom sorting function can be utilized

var popularToys = [
    "cards", "pogo-stick"
]

var data = {
  "toys": [
    {
      "name": "car",
      "price": "10"
    },
    {
      "name": "duck",
      "price": "25"
    },
    {
      "name": "pogo-stick",
      "price": "60"
    },
    {
      "name": "cards",
      "price": "5"
    }
  ]
};

function popularFirst(a, b) {
  var aIsPopular = popularToys.indexOf(a.name) > -1;
  var bIsPopular = popularToys.indexOf(b.name) > -1;
 
  if (aIsPopular) {
    // b could be popular or not popular, a still comes first
    return -1;
  } else if (bIsPopular) {
    // a isnt popular but b is, change the order
    return 1;
  } else {
    // no change
    return 0;
  }
}

console.log(data.toys.sort(popularFirst));

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

Can PHP's CURL handle cookies?

Recently, I set up a poll using PHP that allows voting without the need for an account. However, I became concerned about the possibility of the poll being vulnerable to hacking and spam votes. I discovered that I could potentially vote multiple times by ...

Struggling with JQuery to revert an element back to its original position after the mouseout event

Hello all, I'm a newcomer here and I've been trying my hand at some basic JQuery. However, I've encountered an issue that I could use some help with. Have you ever come across those boxes on websites where when you hover over them, an arrow ...

Rendering Local HTML with local styling and scripts in React Native Webview

I am having trouble loading a local HTML, CSS, and JS file in my React Native webview. The CSS is not being applied to the HTML. Here is my folder structure: https://i.sstatic.net/mqYT9.png My HTML file, along with CSS, images, and JS file are all placed ...

Utilizing a React Hook to set data by creating a pure function that incorporates previous data using a thorough deep comparison methodology

I have come across the following code snippet: export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} & ...

An issue arises when ng-pattern fails to recognize a regular expression

My form includes inline validation for a specific input field. <form name="coForm" novalidate> <div> <label>Transaction: </label> <input type="text" name="transaction" class="form-control" placeholder="<Dir ...

Using the express.Router instance for handling errors can be a useful tool in your development

Based on the documentation, it states that any nodejs express middleware function has the capability of being swapped out by App or Router instances: Given that router and app adhere to the middleware interface, they can be used just like any other midd ...

Tips for safely storing JWT in the browser

I am currently working with Angular 10 on the front-end and obtaining a JWT from backend services. I am seeking the best method to securely store my Okta JWT in the browser while also mitigating the risk of XSS and XSRF attacks. I have looked into storing ...

AngularJS: The delay in updating variable bindings following a REST API call

When utilizing a REST service, I wanted to implement a variable to show whether the service is currently loading or not. Controller $scope.loading = true; $http.get('/Something'). success(function(data, status, headers, config) ...

Utilizing the change function in conjunction with that

My attempt at creating a simple function to implement the change function didn't go as planned:/ What I am trying to achieve: 1- When a cost checkbox is checked, assign the corresponding cost (e.g., cost1.checked ? cost1 = 10 : 0) 2- Calculate and di ...

Assign a variable to the result of ajax that remains unchanged until it is specifically invoked

I am currently working on the final part of my radio script, specifically focusing on the "last song" section. My goal is to retrieve a URL from an external PHP script, play the song, and once the song ends, I want to set a global variable equal to the cur ...

What are the steps to generating and sharing 'npm create' scripts?

I am looking to develop and release a script on npm that functions similarly to: npm create qwik@latest or yarn create next-app --typescript However, I am unsure where to begin. Despite searching extensively online, I have not been able to find any helpf ...

Exploring the concept of upserting records using the MongoDB $

I am working with two collections in my database: Regions and Registrations. var RegionSchema = new Mongoose.Schema({ name: {type: String}, registrations: [{type: Mongoose.Schema.Types.ObjectId, ref: 'registrations'}], ... }); The Registr ...

The socket.io-client could not be located on the running Node.js server

Setting up a fresh installation of Node, Express, and Socket.io on a Linux environment using npm. When attempting to run a sample from the official socket.io source, I encountered an error stating that the 'socket.io-client' module was not found ...

Issues with the execution of Typescript decorator method

Currently, I'm enrolled in the Mosh TypeScript course and came across a problem while working on the code. I noticed that the code worked perfectly in Mosh's video tutorial but when I tried it on my own PC and in an online playground, it didn&apo ...

Completing online form text entries in WebView without the need for identifying elements

I am currently working on a project to automate filling out an online login form using local string variables. This is the progress I have made so far: web = (WebView) findViewById(R.id.webview); WebSettings webSettings = web.getSettings() ...

How to search for a value in Firebase database and save it to an HTML table?

I am working on fetching specific values from my 'snapshot' and storing them if they exist. Below is the snippet of my code: function paydata(){ firebase.database().ref("pay/0/0/").once('value', function(snapshot){ var resp ...

Exploring the capabilities of require() in nodeJS

I'm wondering about the inner workings of the require() function in a nodeJS application. What exactly does require() return? Let's say I want to utilize two third-party packages: lodash and request. After installing these packages, my code mig ...

Connecting Angular directive to a controller

While diving into some Angular JS tutorials, I decided to apply what I learned in the Ionic framework. Unfortunately, I hit a roadblock when attempting to create a reusable HTML control because the model isn't syncing with the view as expected. Here&a ...

How can I get my view to render in node.js/express using XMLHttpRequest()?

After working on my node/express app for the past three days, I am still facing an issue with making a GET request to a specific route from the client side. Despite using XMLHttpRequest and setting the necessary headers for authorization, the app remains s ...

Adjust the size of an input field in jquery or javascript based on user input

Ensure that an input text box can only contain a maximum of 13 numbers, but if the user enters a 14th number as a decimal point, then allow up to 16 numbers. HTML: <input type="text" maxlength="15" onkeyup="checkCurrency(this)"/> Script: func ...