The find() function in JavaScript fails to identify duplicate values within an array of objects

I have created a bookmark feature with the following functionality:

  $scope.bookmarkPost = function(bookmark_post){
    if(window.localStorage.bookmarks == null) {
      user_bookmarks = [];
    } else {
      user_bookmarks = JSON.parse(window.localStorage.bookmarks)
    }

    var existing_post = find(user_bookmarks, function(post){ return post.title == bookmark_post.title; });

    if(!existing_post){
      user_bookmarks.push({
        id: bookmark_post.pagid,
        title : bookmark_post.title,
        date: bookmark_post.created,
        room: bookmark_post.room
      });
    }

    console.log(JSON.stringify(user_bookmarks));

    window.localStorage.bookmarks = JSON.stringify(user_bookmarks);
  };

This implementation should add the post to an array of objects and store it in the local storage. I attempted to check for duplicate entries by comparing titles like this:

var existing_post = find(user_bookmarks, function(post){ return post.title == bookmark_post.title; });

To be transparent, I am uncertain about the exact purpose of this code snippet, but I haven't found any alternative solutions yet. Unfortunately, this check is not functioning properly, resulting in duplicate entries. Any suggestions on how to resolve this issue?

Answer №1

If you're looking for a way to locate a specific element in an array, you may want to consider using the Array.find() method:

var selected_item = my_array.find(function(item){ 
  return item.id === selected_id; //use === for strict comparison
}); //will only find the first matching element based on the callback criteria

Keep in mind that Array.find() does not have support in Internet Explorer.

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

Vertical tab design in Bootstrap does not automatically switch tabs

I'm managing two separate tab boxes that switch content when clicked or over a 5-second period. https://i.sstatic.net/Ujz9H.jpg https://i.sstatic.net/sFc1K.jpg The left box is functioning correctly, but the right box is changing the active state wit ...

Having trouble with AngularJS ngRepeat not functioning properly?

Currently, I am utilizing AngularJs to showcase Google maps with markers. Upon clicking a marker, I am aiming to display the details of the clicked marker. Here is the content of my Controller.js: function createMarker(latitude,longitude,name,address,lo ...

Deactivate fields B and C unless input A is provided

http://jsfiddle.net/6Pu3E/ JavaScript Code: $(document).ready(function() { var block = false; if ($('#password').attr('disabled')) { block = false; } else { block = true; } if (block) { $(&a ...

Issue with Twilio's sendMessage function: it is not successfully delivering messages to every value within

I am encountering a problem with Twilio failing to send a message to all the values in an array. var index; var a = req.body.numbers; console.log(a); if (req.body.numbers.indexOf("undefined") > -1) { console.log("No numbers stored"); } else { for ...

Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code ...

Extract the content from a widget on a different site

How can I eliminate the specified text shown in the image? https://i.sstatic.net/174fD.png This widget is sourced from an external website. Is it possible to use javascript to wrap a around the text and then remove it using css? It's important to ...

Pattern matching without any specific order in a PostgreSQL array field, with the ability to use 'OR' for conditions

Summary I am currently developing a data analysis tool that interacts with a PostgreSQL database and is capable of constructing SQL queries to filter rows based on user input. Each row in the database represents a record containing input data and correspo ...

Customizing the background color in TurnJSIncorporating

Recently, I encountered a problem that has left me puzzled. Despite searching online for help, I have not been able to find a solution. The issue lies with the basic code provided on the official page of the TurnJS script. <div id="flipbook"> <di ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

Karma Unit: Evaluating keypress functionality utilizing the escape button

Within my directive, I have the following code: $document.bind('keydown', function ($event) { if ($event && $scope.visible && $event.which === escapeKey) { $scope.toggle(); $scope.$apply(); } }); I am looking to te ...

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...

Conceal or reveal input elements with a toggle function in jQuery by utilizing

When the user chooses an option from a dropdown list, I want to display or hide different input fields accordingly. I attempted to use toggle with boolean values, but it doesn't seem to be working as expected. I expect that if I send 'true' ...

Are there any PHP methods available for imploding an associative array while retaining the keys intact?

Explaining the title of this query is unnecessary. I've been told that I can achieve this by using http_build_query, but I prefer a specific function for this purpose. Here is an example of the input: $assoc = array( "fruit" => "banana", ...

Data table created with functional components is not refreshing when columns are added or removed, which are stored in the state as an array of objects

I’ve been working on setting up a datatable with a checkbox dropdown feature to add or remove columns from the table. Everything is functioning properly, except for one issue – the table is not refreshing unless I click on one of the header titles. At ...

Is there a workaround for unresolved symlink requirements when using npm link?

Creating an NPM package often involves using the following: npm link This allows for making modifications to a package called <myPackage> during development without constantly having to publish and unpublish! Developers can make changes locally and ...

Setting up a React application and API on the same port: A step-by-step guide

I have developed a React app that fetches data from a separate database through an API. While testing the app locally, it runs on one port while the API runs on another port. Since I need to make AJAX calls from the app to the API, I have to specify the ...

What is the best way to link multiple return statements in Node.js using ioredis?

Currently utilizing ioredis and interested in retrieving the path and value shown in the code snippet below up to the anonymous function. console.log( function (jsonGraphArg) { return Redis.hget(jsonGraphArg[0], jsonGraphArg[1], function(error ...

Keep track of the current state as the page changes with React Router

I am experiencing an issue with my React component. const Page = React.createClass({ getInitialState() { return { page: {} }; }, componentDidMount() { const pageId = this.props.params.pageId; socket.emit('get page', pageId, (pa ...

PHP allows for dynamic options in a select based on the selection in another select element

Is there a way to convert a dropdown menu with multiple levels into three select boxes using pure PHP? For example, selecting the main menu would only display the corresponding submenu options in the next select box, and then choosing a submenu option wo ...

There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets upload ...