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

SecretKey is not valid, FirebaseError code: 400

Currently, my backend is powered by Firebase. However, when I initiate it using NODE_ENV=debug firebase emulators:start --inspect-functions, the following messages are displayed: emulators: Starting emulators: auth, functions, storage ⚠ functions: Ru ...

JavaScript has the ability to manipulate the width of an element by using methods to both retrieve

I have a unique situation where I need to dynamically adjust the width of a ul list element based on the text content inside it. Specifically, I want the width of the ul list to be equal to the width of the first list item, which can change frequently. My ...

spill the elements from one div into another div

I'm facing a situation where I have 2 divs on a page, with the first div containing text content only. The issue is that when the content of the first div overflows, it gets cut off due to the CSS applied to it: .one { overflow: hidden; width: 1 ...

Optimal method for conducting Jasmine tests on JavaScript user interfaces

After exploring the jasmine framework for the first time, I found it to be quite promising. However, I struggled to find a simple way to interact with the DOM. I wanted to be able to simulate user interactions such as filling out an input field, clicking ...

Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data. var app = angular.module("Recib ...

Display data in an HTML table based on user search input using Angular

I am currently working on integrating a JSON file into my project, which will eventually be accessed through an API from a server. Right now, I am pulling data directly from an object. My goal is to build an HTML file that features a table with navigation ...

Update the button text dynamically when clicked without using an identifier or a class

If we take a look at my button in the following code: <input type="button" value="BLUE" name="button_blue" /> My goal is to have the value="BLUE" changed to value="RED" or any other desired value when the button is clicked. ...

Having trouble with transferring information from JQuery to PHP

Currently, I'm working on transmitting data from jQuery to PHP. Here's an excerpt of what I've done: var jsonArray = JSON.stringify(dataArray); $.ajax({ type: "POST", url: "addcar_details.php", ...

How is it possible for TypeScript to enable the importing of dependencies that it ultimately cannot utilize during runtime?

Take a look at my sample project by following this link: https://github.com/DanKaplanSES/typescript-stub-examples/tree/JavaScript-import-invalid I have developed a file named main.ts: import uuid from "uuid"; console.log(uuid.v4()); While type ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

Error in Express Post Request: Headers cannot be modified after being sent to the client

I am a beginner in Node.js and I am facing some challenges while working on an app for learning purposes. I encountered the following issue: Error: Can't render headers after they are sent to the client. I am unsure of how to resolve it. C:\Us ...

The integration of angularFileUpload seems to be malfunctioning

This question may seem simple, but I am new to using Angular. My goal is to upload images on my website using AngularFileUpload. Here is what I did when initializing my app: var app = angular.module('myApp',['ui.router'],['angular ...

How can you utilize the Array submission syntax within HTML coding?

I currently have numerous input fields within a form, and some of them are structured like this: <input name="agents[]" type="file" /> Additionally, imagine there is a plus button next to this field as shown below: <img src="plus.jpg" id="some_ ...

I am struggling to decide which attribute to use for implementing image swap on mouseover() and mouseout()

I have a problem using jQuery to switch between images when hovering on and off. Here's the code snippet I'm working with: HTML <img class="commentImg" src="images/comments.png" data-swap="images/comment_hover.png" alt=""> jQuery $(" ...

Issue with Ajax communication to PHP script causing data not to be sent

I am developing a web application that functions as an extensive form which will later be converted into a PDF document. Upon submission of the form, all input data is sent to a PHP file where they are stored as variables to be included in the PDF. Some of ...

Utilizing Mantine dropzone in conjunction with React Hook Form within a Javascript environment

Can Mantine dropzone be used with React hook form in JavaScript? I am currently working on a modal Upload using Tailwind components like this import { useForm } from 'react-hook-form'; import { Group, Text, useMantineTheme } from '@mantine/c ...

Encountering difficulties in applying a dynamic aria-label to the md-datepicker component

I am currently utilizing the md-datepicker feature in my project. You can check out how it works here: https://material.angularjs.org/latest/demo/datepicker However, I am facing an issue where I am unable to dynamically add a value to the aria-label attri ...

How can I identify duplicate values within two distinct javascript objects?

Consider two sets of JavaScript arrays containing objects: var allUsers=[{name:"John",age:25},{name:"Emily", age:30},{name:"Michael",age:22}] and var activeUsers=[{name:"John",status:"active"},{name:"Sarah", status:"active"}] I am attempting to iterat ...

How can I use vanilla JavaScript to retrieve all elements within the body tag while excluding a specific div and its descendants?

My goal is to identify all elements within the body tag, except for one specific element with a class of "hidden" and its children. Here is the variable that stores all elements in the body: allTagsInBody = document.body.getElementsByTagName('*&apos ...

Ionic, Angular - A component with two out of three inputs displaying undefined values

I am facing an issue with the @input() in my code. Two out of three inputs have undefined values when I try to use them, although they can be displayed using interpolation in the template file. .ts : export class NoteCanvasPageComponent { @Input() note ...