Determine if an array contains a specific value

I have a collection of objects and I want to ensure that no duplicate objects are added. I attempted the following code to detect duplicates:

const array = [{ name: 'John' }];

const newName = {
  name: 'John'
};
console.log(array);
console.log(newName);

if (array.includes(newName)) {
  console.log(newName.name + ' already exists');
} else {
  console.log('name does not exist');
}

Upon logging, it shows that the object NewName is identical to array[0]. However,

if(array.includes(newName))

yields false.

What am I doing incorrectly? I also tried the suggestions in this thread without success:

How do I check if an array includes an object in JavaScript?

Answer №1

To easily check for a specific item in an array, you can utilize the array.some method which is well-documented in the Array.prototype.some() documentation.

If we consider a personalized example, there are some adjustments that can be made to enhance your program:

const array = [{ name: "John" }];

  const newName = {
    name: "John"
  };
  console.log(array);
  console.log(newName);

  if (array.some(object => object.name === newName.name)) {
    console.log(newName.name + " exists");
  } else {
    console.log("name does not exist");
  }

Answer №2

If the name serves as the unique identifier for an object, you can utilize the some function on an array:

const array = [{ name: 'John' }];    
const newName = { name: 'John' };

if (array.some(({name}) => name === newName.name)) {
  console.log(newName.name + ' exists');
} else {
  console.log('name does not exist');
}

Alternatively, you can verify if the number of properties is the same and then compare each property using:

const array = [{ name: 'John', age: 33 }, { name: 'John', age: 45 }];    
const newName = { age: 33, name: 'John' };

if (array.some(x => Object.keys(x).length === Object.keys(newName).length && Object.keys(x).every(p => x[p] === newName[p]))) {
  console.log(newName.name + ' exists');
} else {
  console.log('name does not exist');
}

Answer №3

The key point to note here is that includes evaluates object identity, not just properties. While newName may have the same properties as an object in your array, they are distinct objects much like two individuals with the name John are separate people. For a clear demonstration, try running {} == {} and observe the result returns false.

To determine if the array contains an object with a matching name, you can utilize some method by providing a comparison function, for instance:

array.some(e => e.name === newName.name)

Answer №4

try this out :

let personName = {
  firstName: 'John'
};
console.log(array);
console.log(personName.firstName);
let isFound = array.some(object => object.name === personName.firstName);

if (isFound) {
  console.log(personName.firstName + ' is present');
} else {
  console.log('name does not exist in the array');
}

Answer №5

const array = [{
  name: 'John'
}];

const newName = {
  name: 'John'
};

let resultArr = array.filter((item) => {
  return item.name === newName.name
})

let elementPresentMsg;

if (resultArr.length > 0) {
  elementPresentMsg = newName.name + ' exists';
} else {
  elementPresentMsg = 'name does not exist'
}

document.getElementById('msg').innerHTML = elementPresentMsg;
<html>

<body>

  <p id="msg"></p>

</body>

</html>

If you are looking to match attributes of an object in an array, the code below can be useful:

const array = [{ name: 'John' }];

const newName = {
  name: 'John'
};

let resultArr = array.filter((item) => {
    return item.name === newName.name
})

if (resultArr.length > 0) {
  alert(newName.name + ' exists'); // Instead of alert, find a way to print the result
} else {
  alert('name does not exist'); // Instead of alert, find a way to print the result
}

Answer №6

The reason for this is because array[0] and newName are not the same in Javascript. They are referring to different elements, hence when you try console.log(array[0] == newName), it will return false.
To identify duplicates, you can use the following approach:

if (JSON.stringify(array).indexOf(JSON.stringify(newName)) != -1) {
  console.log('Duplicate exists')
}
else {
  console.log('No duplicate found')
}

Answer №7

When attempting to compare two different instances of objects, they will never be equal.

To enable deep comparison, you can convert the objects to primitive strings using JSON.stringify and then utilize Array.includes. As highlighted by ttulka, this method only works if the object being searched has properties in the same order as the object being sought in the array.

const array = [{ name: 'John', age: 33 }];
const newName = {
  name: 'John',
  age: 33
};
if (array.map(obj => JSON.stringify(obj)).includes(JSON.stringify(newName))) {
  console.log(newName.name + ' exists');
} else {
  console.log('name does not exist');
}

Referencing the Array#includes polyfill on MDN reveals that the comparison is based on the strict equality operator ===:

function sameValueZero(x, y) {
   return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}

// 7. Repeat, while k < len
while (k < len) {
  // a. Let elementK be the result of ? Get(O, ! ToString(k)).
  // b. If SameValueZero(valueToFind, elementK) is true, return true.
  if (sameValueZero(o[k], valueToFind)) {
      return true;
  }
  // c. Increase k by 1. 
  k++;
}

Therefore, comparing two separate object literals using === will result in inequality:

console.log({name :"John"} === {name :"John"});

In contrast, primitive strings are considered equal when compared with ===:

console.log('{name:"John"}' === '{name:"John"}');

However, the same principle does not apply to String objects:

console.log(new String('{name:"John"}') === new String('{name:"John"}'));

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

Is there a way to keep the selected option in handlebar permanently, even after multiple page refreshes?

I am having trouble implementing the drop-down menu option in handlebars using jQuery. Therefore, I have opted to use the select-options menu instead. Here is the code snippet: <select name="sources" id="sources" class="custom-s ...

Angular with Firebase integration and user-specific data features

Whenever I look at my code below, I am able to successfully add a project and link it with the user. However, whenever I try to retrieve a user's projects, I keep encountering this error: TypeError: undefined is not a function I have also attempted ...

Beware: The use of anonymous arrow functions in Next.js can disrupt Fast Refresh and lead to the loss of local component state

I am currently encountering a warning that is indicating an anonymous object in a configuration file, and even specifying a name for it does not resolve the warning. Below you will find the detailed warning message along with examples. Warning: Anonymous ...

Stop music with one click, code in Javascript

I am encountering an issue with a set of 5 div boxes on my website. Each box is supposed to play a specific audio track when clicked, based on data attributes. However, I'm having trouble pausing the previous track when clicking on a new box, resultin ...

Tips for preventing the occurrence of a final empty line in Deno's TextLineStream

I executed this snippet of code: import { TextLineStream } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7201061632425c4341445c42">[email protected]</a>/streams/mod.ts"; const cm ...

The conversation reappearing prematurely before a response is chosen

Incorporating a dialog box that prompts the user with a question is crucial in this function's design. The code snippet below illustrates how it operates: function confirmBox2(action) { var message = ""; if (action == "Quit") { mess ...

Implementing Ajax calls to dynamically update Datatable results

Currently integrating Datatables.js with an ajax call for data retrieval. The json response I'm receiving is as follows: "success":true,"message":"","items":[{"id":"1","ip_address":"127.0.0.1","email... My data is stored within the data.items array ...

Combining numerous words from a dataset using HTML and Javascript

I'm attempting to include a text from a button into a modal window. Currently, it is working; however, if the data consists of more than two words, only the first word is displayed. What am I doing incorrectly? ... <button type="submit" class="ob ...

Tips for retrieving specific information from Wikipedia using AJAX

Is there a way to retrieve the information consistently displayed in the right box during searches using AJAX? I've tried using the Wikipedia API, but haven't been able to find the specific information I need. https://i.sstatic.net/wqJEc.png ...

Exploring each list item within the specified unordered list

Here is a basic code snippet: var ulreq = $("#abc").children("ul.ghi"); var lists = ulreq.find("li"); for( var i = 0; i < lists.length; ++i){ alert(lists[i].text()); // Display the values in these li }<script src="https://ajax.googleapis.com/ajax ...

Find the accurate street view on Google Maps URL without relying on computeheading

I've implemented the computeHeading code from a previous answer by Geocodezip, which is mostly effective but has some minor issues that are not related to Geocodezip. The resulting value from computeHeading is stored in the "heading" variable, which d ...

The ng-option feature has taken over as the new default option

My select tag looks like this: <select ng-model="vm.fooModel" ng-options="item.id as item.name for item in vm.fooOptions" > <option value="none">Select</option> </select> The problem arises when angular 1.6 renders ...

I seem to be stuck in an endless loop within React and can't find a way to break free

Currently, I am utilizing the useState() function along with an array errors[] as part of the state and a function setError() to pass the useState() function to child elements for calling purposes: const [errors, setErrors] = useState([]); //-------------- ...

The Node.js server pauses its listening activities until the promise, which involves an asynchronous function that runs a loop with the goal of making it operate in the background, is

My server code is set up to listen on a specific port: app.listen(PORT, () => { console.log(`Server running on ${PORT}`); }); When a request is received, it is sent to a function for processing: app.get("/", (req, ...

Grouping object properties in a new array using Java Script

I'm currently learning Java script and attempting to merge an Array of objects based on certain properties of those objects. For instance, I have the following array which consists of objects with properties a, b, c, pet, and age. I aim to create a n ...

What is the best way to retrieve the IDs of selected items in jQuery selectables?

I have a straightforward question that I've been struggling to find an answer to. When using jQuery selectables, I want to retrieve the ID of the selected list item when it's clicked. Here is an example of my list: <ol id="selectable"> ...

Exploring the contrast in importing CSS between the HTML header, JS file, and Vue Component

Exploring the world of Vue with webpack, I find myself curious about the various ways to import CSS. It appears that there are three methods for importing CSS: Adding style sheets directly to HTML headers: <link type="text/css" rel="stylesheet" ... &g ...

Updating an element within an array in a Mongoose database: A step-by-step guide

Currently, I'm looking to make updates to the "like" attribute within an array stored in my mongoose database. { "_id" : ObjectId("59c7eb0c4a992f8702d847a4"), "title" : "Favorite Rapper", "token" : "9b3fd295a1", "votes" : [ { ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...

Utilizing jQuery datepicker to extract data from a database and trigger an Alert: A tutorial

I want to create an alert that pops up when someone chooses a specific date on a calendar. The information displayed in the alert needs to be retrieved from a database, not just showing the selected date. I have been able to display a basic alert, but I ...