Underscore - Evaluating the differences between two arrays of objects (positions)

Is it possible to compare arrays based on the changes in their element positions?

I have an original array of objects that has one of its elements' values changed, resulting in a new array:

   origElements = [{id: 1, value: 50}, 
                   {id: 2, value: 60}, 
                   {id: 3, value: 70}]

changedElements = [{id: 1, value: 50},
                   {id: 3, value: 60}, 
                   {id: 2, value: 120}]


var diff = _.difference(_.pluck(origElements, "id"), _.pluck(changedElements, "id"));
var result = _.filter(origElements, function(obj) { return diff.indexOf(obj.id) >= 0; });

In this scenario, 'result' would not yield any results because there are no differences in values between the arrays [1, 2, 3] and [1, 3, 2]. I am looking to implement a 'strict difference' that considers the index as well, providing information on the new order of the objects.

Answer №1

Consider approaching the problem in this manner:

let originalItems = [{
    id: 101,
    value: 30
}, {
    id: 102,
    value: 40
}, {
    id: 103,
    value: 50
}];

let modifiedItems = [{
    id: 101,
    value: 30
}, {
    id: 103,
    value: 45
}, {
    id: 102,
    value: 80
}];

let originalItemIds = _.pluck(originalItems, "id");
let modifiedItemIds = _.pluck(modifiedItems, "id");
console.log("Do the array elements retain their positions?",
    originalItemIds.join() === modifiedItemIds.join());

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

When trying to upload a file using multer, an error occurred stating "Unexpected field

My current issue involves using multer to upload an image from a form. However, I am encountering an Unexpected field error after uploading the image. In my HTML code, I have specified the file and file-model names as myFile. app.js var express = re ...

Place form at the center of the Bootstrap Modal

My question is, how can I center the entire form, including the input fields and labels, within the modal? Here is also a helpful Fiddle: http://example.com, although the snippet provided should work as well. <script src="https://example.com/bootstr ...

Changing the boolean value of User.isActive in Node.js: A step-by-step guide

Define a User Model with isActive as a Boolean property. Upon clicking a button, the user is redirected to a route where their information is retrieved based on the id from the parameters. Once the user is found, the script checks the value of isActive. ...

Switch out a character with its corresponding position in the alphabet

Starting out, this task seemed simple to me. However, every time I attempt to run the code on codewars, I keep getting an empty array. I'm reaching out in hopes that you can help me pinpoint the issue. function alphabetPosition(text) { text.split ...

Can a specific CSS rule be written in Material UI using makeStyles that will only apply if the element has both classes together?

It's common knowledge that achieving this in CSS is a possibility. .makeStyles-mainNavWrapper-67.sticky{ position: fixed; top: 0px; opacity: 1; transition: opacity 1s ease; padding: 10px; } I am curious to find out if this can be achieved ...

ESLint has detected a potential race condition where the `user.registered` variable could be reassigned using an outdated value. This issue is flagged by the `require-atomic-updates` rule

I have developed an asynchronous function which looks like this: let saveUser = async function(user){ await Database.saveUser(user); if (!user.active) { user.active = true; //storedUs ...

Incorporating an HTML file into a DIV container while also displaying menu links

I am facing a major challenge with what I recognize as a relatively simple issue for experts. As someone who is still learning, I am struggling to create menu links that load an HTML file into a specific DIV. Despite my efforts, the content keeps loading i ...

Is there a way to extract values from a particular object?

Currently, I am utilizing a JSON server to establish a straightforward login system. The data stored on the server is structured as follows: { "users": [ { "name": "user1", "password": "pass1", "email": "<a href="/cdn-cgi/l/emai ...

What is the best way to generate page elements in AngularJS when the total number of pages is already known?

I have a project where I am developing an application that showcases a JSON of "users" in an HTML5 table. This application is built using Bootstrap 3 and AngularJS. My goal is to implement pagination for this table. Instead of having an array to iterate t ...

Creating a Seamless Bond Between JavaScript and HTML

I've been struggling to find a helpful and straightforward solution to a simple problem. On my web page, I have five image placeholders that should be filled with one of nine random pictures. To achieve this, I wrote a JavaScript code that generates r ...

Automatically activate the Focus Filterfield in the ng-multiselect-dropdown upon clicking

I've integrated the ng-multiselect-dropdown package into my Angular project using this link: https://www.npmjs.com/package/ng-multiselect-dropdown. Everything is functioning as expected, but I'm looking to automatically focus on the filter input ...

developing a fresh node within the jstree framework

Recently, I have been working on creating a node using crrm as shown below $("#TreeDiv").jstree("create", $("#somenode"), "inside", { "data":"new_node" }); This specific function is triggered by a wizard, enabling me to seamlessly create a new node withi ...

Design a unique UIButton that can be customized to display various data points

I am facing a challenge with displaying an array of content. The issue is that creating a button for each item in the array is not practical, especially if the array has many items. I am seeking help to come up with a solution to generate a single button t ...

The issue of a jQuery slider malfunctioning when using an https URL on a Wordpress website

My WowSlider is experiencing issues on the main page of my Wordpress website with https. The images in the slider are stacked statically one after another. However, when the site is accessed with http, the slider works perfectly with the expected transitio ...

Showing a series of words individually on separate lines using the IN and OUT flags

I wrote a program that is capable of storing multiple lines entered by the user and then checking for new words to print on new lines. Here's the code I used: #include<stdio.h> #define IN 1 //inside a word #define OUT 0 //outside a word in ...

Using GraphQL to set default values in data within a useEffect hook can lead to never

Here's the code snippet that I'm working with: const [localState, setLocalState] = useState<StateType[]>([]); const { data = { attribute: [] }, loading } = useQuery<DataType>(QUERY, { variables: { id: client && client.id ...

Tips for incorporating a live URL using Fetch

I'm having some trouble with this code. Taking out the &type = {t} makes it work fine, but adding it causes the fetch to not return any array. let n = 12 let c = 20 let t = 'multiple' let d = 'hard' fetch(`https://opentdb.com/ ...

Tips on sending a function's return value to an object in Node.js

I'm currently exploring Node.js and working on a REST API for a project. One of the functionalities I am implementing is a post request to store form data in a database. Some values will be retrieved from the form data while others will be generated ...

The elegant scroll-bar (whether directive-based or not) seems to be having trouble functioning within the ng-view

I am looking to add a stylish scroll bar to a paragraph that is located within the ng-view. My module code appears as follows: var myweb = angular.module('myweb' , ['ngRoute', 'perfect_scrollbar']); myweb.config(function($ro ...

"Exciting Changes in Color According to the Active State of vue-route-link

I am trying to find a way to customize the CSS based on whether a link is exact or active. Essentially, when a user clicks on a menu item, I want the underline to change depending on whether the link is an active router-link. Although I was able to accompl ...