Ways to shift duplicates to the beginning of an Object array?

I am working with a variable that contains an array of objects

let Obj1 =

    [
    {Id: 123, name: 'A'},
    {Id: 124, name: 'B'},
    {Id: 125, name: 'C'},
    {Id: 126, name: 'D'},
    {Id: 127, name: 'E'}
    ]

let Obj2 = {Id:126, name: 'D'}

Is there a way to dynamically move Obj2 within Obj1 to the 0th index using Javascript or TypeScript? Obj2 is received from the backend and Obj1 is data already present in the frontend. The desired end result should look like this:

[
{Id: 126, name: 'D'},
{Id: 123, name: 'A'},
{Id: 124, name: 'B'},
{Id: 125, name: 'C'},
{Id: 127, name: 'E'}
]

Answer №1

const dataObj =
    [
    {id: 111, name: 'X'},
    {id: 112, name: 'Y'},
    {id: 113, name: 'Z'},
    {id: 114, name: 'W'},
    {id: 115, name: 'V'}
    ];

let searchObj = {id:114, name: 'W'};

let filteredArray = dataObj.reduce((result, item) => (item.id === searchObj.id ? result.unshift(item) : result.push(item), result), []);

console.log(filteredArray);

Answer №2

let object1 = [
        {Id: 123, name: 'A'},
        {Id: 124, name: 'B'},
        {Id: 125, name: 'C'},
        {Id: 126, name: 'D'},
        {Id: 127, name: 'E'}
    ]
    
let object2 = {Id:126, name: 'D'}

for (let index = 0; index < object1.length; index++) {
    if (object1[index].Id === object2.Id && object1[index].name === object2.name) {
        object1.splice(index, 1)
        object1.unshift(object2)
        break
    }
}

console.log(object1)

Answer №3

To organize the data, you can use property comparison.

const
    compareValues = (x, y) => x.Id === y.Id && x.name === y.name,
    items = [{ Id: 123, name: 'A' }, { Id: 124, name: 'B' }, { Id: 125, name: 'C' }, { Id: 126, name: 'D' }, { Id: 127, name: 'E' }],
    target = { Id: 126, name: 'D' };

items.sort((x, y) => compareValues(y, target) - compareValues(x, target));

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

Answer №4

Give this a try!

let data = [
   {
      "num":1,
      "letter":"A"
   },
   {
      "num":2,
      "letter":"B"
   },
   {
      "num":3,
      "letter":"C"
   }
]

let newData = {
    "num":2, 
    "letter":"B"
}

/* 

if newData isn't in the data array...
add newData to the beginning of the data array

*/

if (data.indexOf(newData) == -1) {
  data.unshift(newData);
}

Answer №5

Success! It did the trick. Grateful for this solution.

data.unshift(data.splice(data.findIndex(item => item.Id === Obj2.Id, 1)[0]);

Answer №6

Looking to rearrange the position of Obj2 within Obj1? Additional notes are included in the code snippet below.

Give this a shot :

// The starting array
let Obj1 = [
  {Id: 123, name: 'A'},
  {Id: 124, name: 'B'},
  {Id: 125, name: 'C'},
  {Id: 126, name: 'D'},
  {Id: 127, name: 'E'}
];

// Object to locate and move
let Obj2 = {Id: 126, name: 'D'};

// Loop through the original array to shift the targeted object to the first index.
Obj1.forEach((obj, index) => {
  // Verify if Obj2 is present in Obj1 array
    if (JSON.stringify(Obj2) === JSON.stringify(obj)) {
    // Removing the object
    const removedObj = Obj1.splice(index, 1);
    // Placing the removed object at index 0.
    Obj1.unshift(removedObj);
  }
});

// Displaying the updated array
console.log(Obj1);

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

Need to swiftly modify values of css attributes?

Here is a snippet of the code I am working with: <div></div> <button> Go </button> div { width: 50px; height: 50px; border: 1px solid #ccc; } var bgs = ['red', 'blue', 'yellow', 'green&apo ...

Is the number 9933272057275866 truly magical?

I encountered a strange issue that I cannot quite understand. It has left me quite baffled. When I attempt to increase the number 9933272057275866 by 1, it somehow adds 2 instead!!! Here is the code snippet: let test = 9933272057275866; let test2 = test+1 ...

React Typescript does not support the use of React-Router

I'm currently working on a React app that utilizes Typescript. The React version is set to "react": "^16.9.0", and the React-Router version is "react-router-dom": "^5.1.2". Within my App.tsx file, the structure looks like this: const App: React.FC ...

Creating a webpage that loads directly to a specific section of content

After searching online, I couldn't find the solution I was looking for. My goal is to have the visible part of the page load halfway down the actual page. This way, when users visit the site, they can immediately scroll up to see more content. I hope ...

Unable to view Chart.js on the second tab

I'm currently working on two different charts for a project - a bar chart and a line chart. The bar chart is displayed on the first tab, while the line chart is on the second tab. Interestingly, the bar chart functions properly, and when I point the l ...

How can I ensure that a button remains fixed at the bottom of a Material UI React Component?

I am currently working on developing a layout for a web application, and I have encountered an issue that I am struggling to resolve. The structure of my grid is as follows: https://i.sstatic.net/TEU2a.png My goal is to ensure that each section inside t ...

Adding a distinct key and its corresponding value to an array in Vue for a unique

I am attempting to add key-value pairs into an array while ensuring their uniqueness. Currently, I am trying the following approach: for (const [key, value] of Object.entries(check)) { console.log(`${key}: ${value}`); this.inputFields. ...

Finding the data type based on the button clicked with javascript: A beginner's guide

I am trying to work with a PHP function that generates dynamically created divisions. Each of these divisions contains a different data type and a button. How can I extract the data type of a division when the user clicks on the submit button using JavaScr ...

What is the purpose of passing data into the 'success' function of an AJAX request?

Recently, I embarked on a journey to learn jQuery and AJAX, but I found myself tangled in confusion when it came to AJAX requests. To gain practice, I decided to create a simple TodoApp using Node, jQuery, and Bootstrap. While I managed to grasp GET and P ...

Error: Angular JS Service is undefined

I'm currently working on creating an array in my application that is universally accessible through services. Additionally, I have implemented ui-router in my application. In the app.js file, I define the service like this: myFamilyApp.service(&apos ...

Is emitting a side effect event acceptable within an RxJS pipe?

Currently, I am utilizing RxJS within the context of an Angular application. Within my service, there is functionality to reinitialize the entire application with different settings as needed. @Injectable() class BootstrapService{ public initApplicatio ...

The @angular/fire package is unable to locate the AngularFireModule and AngularFireDatabaseModule modules

I am facing some challenges while trying to integrate Firebase Realtime Database into my Angular project. Specifically, I am encountering difficulties at the initial step of importing AngularFireModule and AngularFireDatabaseModule. To be more specific, I ...

Protecting the source code of your Node.js application is just as important

When it comes to the security of the node application, is the source code protected from being viewed by clients like PHP? I am currently working on a website using node.js and I want to ensure that my server files are not accessible to others. While I&apo ...

React App with Material UI V1-beta Integration

I just installed the Create React App example from Material-UI.com. curl https://codeload.github.com/callemall/material-ui/tar.gz/v1-beta | tar -xz --strip=2 material-ui-1-beta/examples/create-react-app Upon installation, I encountered the following erro ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

Retrieve the array from within the string

Any suggestions on how I can extract the array from this string? The current string is: "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']" I need to extract it to look like thi ...

Stopping a NodeJs file running on an Ubuntu server

After enlisting help to install a Js script on my server, I encountered an issue where changes I made to the scripts/files were not reflected in the browser. After scouring the internet for answers for about 24 hours, I discovered that Js scripts need to b ...

Encountering an issue accessing a property retrieved from a fetch request in TypeScript

I am currently dealing with the property success defined in the API (reCAPTCHA). /** * The structure of response from the veirfy API is * { * "success": true|false, * "challenge_ts": timestamp, // timestamp of the challen ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...

What is the best way to showcase an item from an array using a timer?

I'm currently working on a music app and I have a specific requirement to showcase content from an array object based on a start and duration time. Here's a sample of the data structure: [ { id: 1, content: 'hello how are you', start: 0 ...