Create a new array by dynamically generating a key while comparing two existing arrays

One of the features in my app involves retrieving data from an API and storing it in $scope.newz.

The previous user activity is loaded from LocalStorage as bookmarkData.

I am facing a challenge with comparing the contentId values in arrays $scope.newz and $scope.bookmarkData.

My goal is to set bookmarkstate : true only for items that match between these two arrays.

Upon finding matches, I want to include those records in $scope.AllnewsList.

Take a look at the code snippet below:

if(data.Status.ResponseCode == 200)
  { 
    $("#fetchnews").hide();

    // $("#nodata").show();

    $("#sError").hide();

    //$scope.AllnewsList =  data.contents;

    $scope.newz = data.contents; 
    $scope.bookmarkData = JSON.parse(window.localStorage.getItem('bookmark'));

    for (var i=0; i < $scope.newz.length; i++)
    {
      for (var j=0; j < $scope.bookmarkData.data.length; j++) 
      {
        if ($scope.newz[i].ContentId == $scope.bookmarkData.data[j].ContentId)
          {
            // console.log($scope.newz[i].ContentId);
            $scope.bookmarkstate == true; 
          }
          else
          {
            $scope.bookmarkstate == false;
          }
      }
    }
    $scope.AllnewsList = $scope.newz;
  }

Answer №1

It seems like you're interested in registering for each newz item, regardless of whether or not you have a bookmark for it.

To achieve this, I suggest setting your $scope.bookmarkstate as an array with the same size as the newz array.

This way, you can track in each cell whether the corresponding cell in the "newz" array has a bookmark or not.

if(data.Status.ResponseCode == 200)
    { 
       $scope.bookmarkstate = [];
       $("#fetchnews").hide();
       $("#sError").hide();
      $scope.newz = data.contents; 
      $scope.bookmarkData = JSON.parse(window.localStorage.getItem('bookmark'));
       for (var i=0; i < $scope.newz.length; i++)
        {
          for (var j=0; j < $scope.bookmarkData.data.length; j++) 
          {
              if ($scope.newz[i].ContentId == $scope.bookmarkData.data[j].ContentId)
               {
                 $scope.bookmarkstate[i] == true; 
              }
              else
              {

                 $scope.bookmarkstate[i] == false;
              }
          }
      }
       $scope.AllnewsList = $scope.newz;
   }

Feel free to let me know how this solution works for you. Cheers!

Answer №2

I have structured the arrays based on the keys you mentioned in your comment and considering the dynamic data provided. If there are any misunderstandings, please feel free to correct me.

var newz = [{contentId : 1, source : 'demoSrc1', title:'title1' },
{contentId : 2, source : 'demoSrc2', title:'title2' },
{contentId : 3, source : 'demoSrc3', title:'title3' },
{contentId : 4, source : 'demoSrc4', title:'title4' },
{contentId : 5, source : 'demoSrc5', title:'title5' },
{contentId : 6, source : 'demoSrc6', title:'title6' },
{contentId : 7, source : 'demoSrc7', title:'title7' },
{contentId : 8, source : 'demoSrc8', title:'title8' }];
//I defined the array 'newz' with static values for simplicity.

var bookmarkData = [{contentId : 1, source : 'demoSrc1', title:'title1' },
{contentId : 4, source : 'demoSrc4', title:'title4' },
{contentId : 6, source : 'demoSrc6', title:'title6' },
{contentId : 8, source : 'demoSrc8', title:'title8' }];
//Similarly, I defined the array 'bookmarkData' with static values.

var AllnewsList = [];


    for (var i=0; i <  newz.length; i++)
    {
      for (var j=0; j < bookmarkData.length; j++) 
      {
            if (newz[i].contentId == bookmarkData[j].contentId)
          {

            newz[i].bookmarkstate = true; 
            AllnewsList.push(newz[i]);
//            console.log(newz[i]);
          }
          else
          {
            newz[i].bookmarkstate = false;
          }
  //        console.log(newz[i].contentId);

      }
    }
console.log(AllnewsList);

Answer №3

Top Tip: To optimize your code and store status efficiently, consider using the underscore (_) for tasks that involve minimizing lines of code.

If I understand correctly, the bookmarkstate array should hold a true value for each news if the news ContentId matches the bookmarkData ContentId; otherwise, it should store false.
var bookmarkstate = [];
var newz = [
    {
        id: 1,
        name: "first",
        ContentId: 3
    },

    {
        id: 2,
        name: "second",
        ContentId: 33
    },
    {
        id: 3,
        name: "third",
        ContentId: 3
    }
];
var bookmarkData = [
    {
        id: 1,
        name: "first",
        ContentId: 3
    },

    {
        id: 2,
        name: "second",
        ContentId: 33
    },
    {
        id: 3,
        name: "third",
        ContentId: 3
    }
];

for (var i = 0; i < newz.length; i++) {
    for (var j = 0; j < bookmarkData.length; j++) {
        if (newz[i].ContentId == bookmarkData[j].ContentId) {
            bookmarkstate[i] = true; // be sure to use the assignment operator
        } else {
            bookmarkstate[i] = false;// remember to use the assignment operator
        }

    }
}
console.log(bookmarkstate);

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

The port has not been defined

My Node server appears to be operational, however the console is displaying an error message stating that the port is undefined. const express = require('express'); const env = require('dotenv') const app = express(); env.config(); ap ...

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

Guide to utilizing jQuery for setting values in all subsequent rows of a table

I have a table with 15 rows of text boxes labeled as text1, text2, and so on up to text15. If I enter text into, let's say, the 5th textbox, I want that same text to be automatically copied into all subsequent textboxes from the 6th through the 15th. ...

A method in JQuery to replace an input with a select element is by using the replace

I have multiple input fields with pre-existing values. My goal is to replace these inputs with select dropdowns that have the same options while retaining the original values. Here is the current HTML structure: <span id="span1"> <input type=" ...

The variable in Vue.js is failing to update, resulting in a "variable is not defined" error

I've been attempting to display the updated value of the totalQuestions variable in the HTML, but I keep encountering the following error. Can someone point out where I went wrong? HTML <label><span class="red-text">Question No: </spa ...

Displaying the specified item within an array using AngularJS

My application features a group of 'players' each with their own unique attributes that I want to showcase within a modal window and cycle through. The user interface is structured like this: <!-- Score Round Modal --> <div class="mo ...

(Typescript) The 'window' property is not present in the 'Global' type

Currently, I am utilizing Mocha/Chai for unit testing and have decided to mock the window object like so: global.window = { innerHeight: 1000, innerWidth: 1000 }; As expected, TSLint is raising an issue stating: Property 'window' does not ex ...

The requestify Node module encounters issues when the body contains special characters

My current project involves the use of node.js and a library called requestify. Here is the snippet of code causing some trouble: console.log('body'); console.log(body); return new Promise(function (f, r) { requestify.request(myurl, { ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

What is the proper way to utilize a filtered object based on its properties within an Angular controller?

Currently, I am working on developing a stacked graph along with its associated table. To retrieve the necessary JSON data, I am utilizing $http.get() and then assigning it to $scope.dataset. Here's a snippet of the HTML: <input ng-model="_search ...

Guide to automatically logging into an AngularJS application using a specific URL

Is there a way to enable auto login using angularjs 1.x? I need the user to be automatically redirected to the home page when they click on a URL sent via email. The URL will contain an email and encrypted password: http://localhost:8080/login/[email ...

pair each instance of a string

Currently, I am developing a todo list application that allows users to add to-do list items and search for specific tasks. My focus at the moment is on refining the search function. Presently, whenever a user searches for a name, only the first task ass ...

Add an image to a div element and determine its height, then apply the height to the CSS property

Here is my JavaScript code that utilizes jQuery: $(".article_big_photo").click(function() { $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()}); $('#screen').show() ...

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...

Having issues getting Nunjucks templates to render correctly in Express

There seems to be an issue with setting up the template hierarchy in Express or possibly an error in how Nunjucks is being utilized. The goal is to have a template that includes common parts and specific pages that extend this template. It appears that the ...

Is it advisable to subscribe to the entire database upon startup in Meteor?

Creating a Meteor app for the internal use of a company, I have designed it to track people and enable managers to assign tasks to various employees. Given the small size of the data being utilized, I anticipate that the database will not grow significantl ...

Guide to retrieving a table field as a one-dimensional array using CodeIgniter's active record query functionality

I currently have a task where I need to fetch user role ids from the user_roles table for a logged-in user. Since a user can have multiple roles, the result is returned in a multi-dimensional array format. To simplify this, I am using a foreach loop to con ...

The button's background color will vanish if you click anywhere outside the button or on the body of

Struggling with a tabpane created using HTML, CSS, and JavaScript. The problem arises when the background color of the active tab's button disappears upon clicking outside the button or on the body. While switching between tabs, I can change the color ...

Choose a row from a table by utilizing AJAX with jQuery

Need help with deleting specific table rows using AJAX? The goal is to send the ID and Printer Type values from the table data cells when a row is selected for deletion. <table class="u-full-width" > <thead> <tr> ...

Utilizing ngIf within HTML comments - a simple guide

My objective is to accomplish the following: <!-- directive: ng-my-if condition --> <link rel="stylesheet" ng-href="myStyle1.css"> <link rel="stylesheet" ng-href="myStyle2.css"> <link rel="stylesheet" ng-href="myStyle3.css"> < ...