Manipulating a JavaScript object array: Eliminating objects with identical properties. Similar circumstances result in varying outcomes

Attempting to remove an object from an array if the age property matches using the provided codes.

 var state= [
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}
  ]
  
  
 let a= [...state];
 var ids=[]

 var ar = a.filter(function(o) {
    
        if (ids.indexOf(o.age) !== -1){
        return false;
        }
        
        else if(ids.indexOf(o.age) === -1){
        ids.push(o);
        return true;}
})
console.log(ids)

    // OUTPUT: (NOT working fine)
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}

However, making a slight alteration by only pushing the age property to the array yields a correct result:

 var state= [
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}
  ]
  
  
 let a= [...state];
 var ids=[]

 var ar = a.filter(function(o) {
    
        if (ids.indexOf(o.age) !== -1){
        return false;
        }
        
        else if(ids.indexOf(o.age) === -1){
        ids.push(o.age); // Here i have edited the code by pushing only age property to the array
        return true;}
})
console.log(ids)

OUTPUT : [23, 25] // Only two items were added.

The conditions in both versions of the code are identical. Strangely, the first version adds 3 items to the empty array while the second version successfully adds only 2 items. How can this inconsistency be explained?

Answer №1

The example provided demonstrates how attempting to match an object's age property using indexOf will not be successful when pushing the entire object into the array. Instead, consider utilizing findIndex for a more effective approach.

var data = [{
    title: "Example A",
    id: 101
  },
  {
    title: "Example B",
    id: 102
  },
  {
    title: "Example A",
    id: 103
  }
]


let newArr = [...data];
var idsArr = []

var filteredArr = newArr.filter(function(item) {
  const index = idsArr.findIndex(id => id.id == item.id);
  if (index !== -1) {
    return false;
  } else if (index === -1) {
    idsArr.push(item);
    return true;
  }
})
console.log(idsArr)

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

Validating Java Answers

I'm trying to implement a feature in my Java program where if a user inputs -1, it will break out of the loop. I'm not sure how to start this process and would appreciate any guidance. The desired output result should look like this: Tax for $1 ...

How can I make rows appear dynamically when the user clicks a button?

I am trying to add rows dynamically when the user clicks on a button. I have created a script for this purpose, but unfortunately, it is not working as expected. Can someone please assist me with fixing it? <script> var i; i = 2; function AddR ...

How to transfer a parameter to a JavaScript function within an Ajax success callback?

While attempting to call the UpdateItem function using AJAX with an anchor tag, I encountered a console error. Error : req is undefined function updateItem(id, desc, vehicleno){ alert("i am here"); $('#ProcessModal').modal(&a ...

What is the best way to manage photos from your phone without having to upload them online?

I'm currently developing an application using AngularJS/Javascript, HTML, and CSS within a cloud-based environment on c9.io. My next task is to create and test an app that can access the phone's photo album, apply filters to images, and I'm ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

Identify data points on the line chart that fall outside the specified range with ng2-charts

I'm struggling to figure out how to highlight specific points on a line chart that fall outside a certain range. For instance, if the blood sugar level is below 120, I want to display that point as an orange dot. If it's above 180, I want to show ...

Personalize the req.body object in Nodejs

I'm curious to know if it's possible to customize the req.body that is sent to MongoDB. Currently, my req.body looks like this: { f_name: 'John', l_name: 'Doe', phone: '4521234892345' } However, I would like it ...

Creating a multi-page form in AngularJS with Tab navigation

Hello, I am currently working on implementing a multi-stage form using AngularJS Tabs. Instead of using routes in this application, I am trying to achieve the desired functionality solely through tabs. app.controller('createProjectController', [ ...

Encountered a problem while trying to implement the jssor slider within an AngularJS application utilizing the

I encountered an issue when trying to use the jssor slider with the ui-view directive The slider functions correctly without AngularJS Uncaught TypeError: Cannot read property 'currentStyle' of undefined" index.html <!DOCTYPE html> &l ...

centered shape-outside within a div

I'm looking to create a layout with paragraphs displayed in columns, with a middle paragraph centered within the parent div. The text of the paragraphs should wrap around the middle paragraph with some margin. Check out the reference photo Below is ...

How come ng-class doesn't apply to a specific class name?

I recently wrote the following code: <style> .dotted { border:dotted; } </style> .... <p ng-style="mystyle" ng-class="dotted">{{ answer }}</p> My intention was to have the paragraph element enclosed within a ...

Unable to convert the String prop that was passed from the parent component to a JSON object using JSON.parse() in a React child component

Issue Overview: The SLTree React component retrieves a JSON object using Ajax, converts it to a string, and then passes it as a property to two other components - Editor and TNode. While the Editor component (which contains CodeMirror) functions correct ...

Storing a ByteArray in the internal storage on Kotlin Android: Tips for Success!

Currently, I am attempting to store a file containing a ByteArray in the internal storage of my Android device using Kotlin. However, all the examples I come across suggest using the following code snippet: val file = File(context.filesDir, name) The issu ...

Tips on obtaining the element selector when a div is being dynamically loaded during an AJAX call

When running two ajax calls, I encounter an issue where the second call loads some HTML onto the page that is needed for processing a specific div in the first call. However, since the div is not present until after the second call is completed, I receiv ...

Optional parameters in Sammy.js

Utilizing ajax for paging has led me to choose Sammy.js, which works well. However, incorporating checkboxes to filter results poses a challenge. While defining a route for Sammy to intercept is feasible, the issue arises when I wish to avoid displaying ce ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

Having trouble retrieving features from a QR code generated with Angularx-qrcode?

I utilized angularx-qrcode in order to create a QR code that displays data from qrInfo. However, I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading 'qrcElement') The code within qr-code-gener ...

Is there a way to ensure my function runs as soon as the page starts loading?

My goal is to have a function execute as soon as a person opens my page, without requiring any interaction. The function should trigger on page load, rather than waiting for a click event. Additionally, I want the function to repeat every 90 seconds. I&apo ...

Not all of the Error constructors are displayed by TypeScript

My issue is straightforward: I am attempting to utilize the Error constructor that requires a message and an options object. Despite setting my tsconfig.json file to have "target": "es2020", the Intellisense in VS Code only displays one ...

"Encountering an issue with TestCafe's Selector - usage of the .find()

I've been having difficulty defining a selector in TestCafe using the ".find" method. My goal is to click on the link "Start a claim" as shown in the image below: https://i.sstatic.net/2BIRK.png Even though I'm using the id element and trying to ...