Javascript: Dive Function Failing to Exclude Intended Element from Array

Having an array with specific data.

console.log(array)

[ Data {
    sample_id: 'S001',
    v_id: 21,
    type: 'BD',
    sf: 'ETV5',
    ef: 'NTRK',
    breakpoint1: '8669',
    breakpoint2: '1728',
    sge: 8,
    ege: 19,
    som: 207,
    wgs: null,
    inframe: 1,
    platform: 'WR',
    rnaconf: 'High',
    reportable: 1,
    targetable: 1,
    path: 'C3',
    evidence: null,
    summary:
     'Same as before',
    comments: null },
  Data {
      sample_id: 'S001',
      v_id: 21,
      type: 'BD',
      sf: 'ETV5',
      ef: 'NTRK',
      breakpoint1: '8669',
      breakpoint2: '1728',
      sge: 8,
      ege: 19,
      som: 207,
      wgs: null,
      inframe: 1,
      platform: 'WR',
      rnaconf: 'High',
      reportable: 1,
      targetable: 1,
      path: 'C3',
      evidence: null,
      summary:
       'Same as before',
      comments: null },
  Data {
      sample_id: 'S001',
      v_id: 21,
      type: 'BD',
      sf: 'ETV5',
      ef: 'NTRK',
      breakpoint1: '8669',
      breakpoint2: '1728',
      sge: 8,
      ege: 19,
      som: 207,
      wgs: null,
      inframe: 1,
      platform: 'WR',
      rnaconf: 'High',
      reportable: 1,
      targetable: 1,
      path: 'C3',
      evidence: null,
      summary:
       'An interesting development',
      comments: null } ]

Analyze the following function:

function diffSummary(o1, o2) {

          res = (o1.sample_id === o2.sample_id) && (o1.v_id === o2.v_id) && (o1.type === o2.type) && (o1.sf === o2.sf) && (o1.ef === o2.ef) && (o1.breakpoint1 === o2.breakpoint1) && (o1.breakpoint2 === o2.breakpoint2);

          res1 = (o1.sge === o2.sge) && (o1.ege === o2.ege) && (o1.som === o2.som) && (o1.wgs === o2.wgs) && (o1.inframe === o2.inframe) && (o1.platform === o2.platform);

          res2 = (o1.rnaconf === o2.rnaconf) && (o1.reportable === o2.reportable) && (o1.targetable === o2.targetable) && (o1.path === o2.path) && (o1.evidence === o2.evidence) && (o1.comments === o2.comments) && (o1.summary !== o2.summary);

          if(res && res1 && res2) {
              return true;
          } else {
              return false;
          }
      }

The purpose of this function is to compare two objects within the array and validate their equivalence except for the summary attribute.

Review the following section of code:

var first = array[0];
var new_array = array.filter(o => (JSON.stringify(o) !== JSON.stringify(first));
var final_array = new_array.filter(o => diffSummary(o, first) === true);

This code snippet eliminates identical elements compared to first from the array. It then removes elements matching first but differing only in the summary attribute from new_array. The expectation is to receive an empty array after these operations.

However, upon printing final_array, unexpected results appear:

[ Data {
      sample_id: 'S001',
      v_id: 21,
      type: 'BD',
      sf: 'ETV5',
      ef: 'NTRK',
      breakpoint1: '8669',
      breakpoint2: '1728',
      sge: 8,
      ege: 19,
      som: 207,
      wgs: null,
      inframe: 1,
      platform: 'WR',
      rnaconf: 'High',
      reportable: 1,
      targetable: 1,
      path: 'C3',
      evidence: null,
      summary:
       'An interesting development',
      comments: null } ]

The analysis of diffSummary showed correctness when assessing first and the last element of array. An issue arises as the last element remains unfiltered.

Any insights would be appreciated.

Answer №1

It then eliminates all elements that are the same as the first element but differ only in terms of the summary value

Your code does not follow this logic, as res2 contains

(o1.summary !== o2.summary)

This condition means you want to include the object if they are different, not exclude it.

Simply change that to === and the output will be empty.

Consider how filter operates:

new_array.filter(o => diffSummary(o, first) === true)

// The elements for which diffSummary function returns `true` will be included in the resulting array by filter.

// So, only when res2 along with res and res1 is true, this condition will be met
// Your current code checks for inequality between o1.summary and o2.summary.

// However, based on your requirement, you should remove them when they are unequal. Therefore, the comparison for `true` needs to be based on equality.

Other notes (apart from the comments above)

1- Line

 var new_array = array.filter(o => (JSON.stringify(o) !== JSON.stringify(first));

contains a syntax error, add one more closing parenthesis ) at the end

2- This logic

 if (res && res1 && res2) {
     return true;
 } else {
     return false;
 }

can be simplified into a single line:

 return res && res1 && res2;

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

After 60 seconds, the AJAX call is returning a 200 status code despite the fact that the server-side process is still

When implementing an AJAX call, I followed this structure: $.ajax({ url: 'download', type: 'POST', data: JSON.stringify(postData), cache: false, contentType: 'application/json;charset=UTF-8' }) . ...

Transferring information from a modal popup to a controller

I am attempting to pass parameters from a Bootstrap modal popup to my controller using Javascript and Ajax. However, when I click the button, it does not seem to work on the controller. How can I successfully send these parameters? Below is the HTML code ...

Swapping out the current div with the outcome from jQuery

I'm attempting to retrieve the most recent data for a div and replace it. The ajax query is fetching the entire HTML page, from which I am locating the right div. Now I want to update the current right div with the new content. $.ajax( { ...

Accessing objects from a sibling component of the parent component in Vue JS

In the structure of my components, the SideHead component contains a method that needs to access objects of Incidents and call functions on them. Simply put, I want a method in "A" to access objects of "B" and invoke their methods. I've considered emi ...

Smooth mobile navigation dropdown animation in Bootstrap

As I put the finishing touches on my website, I encountered a strange problem with the mobile navigation. The menu is set to collapse using Bootstrap 3's collapse javascript. Everything functions properly, except for one issue - when you open the menu ...

I would like to know how to implement a tab component and display pages within tabs in a React JS application

Currently, I am developing a react js application and have created myfirstcomponent to fetch data from a rest api and display it in JSON format. Now, I am looking to enhance my app by adding more components, like mySecondComponent. To organize these compon ...

Using jQuery, Ajax, and HTML together can create dynamic

Is there a way to run JavaScript functions in an HTML file that is loaded using AJAX? The HTML file contains both text and JavaScript, but only the inline JavaScript seems to work (like onclick="dosomething();return false"). The pre-defined functions wra ...

Utilizing Environment Variables during the build process in a VueJS project

During the build stage of a CI job for my VueJS app, I am attempting to utilize an environment variable provided by GitLab CI called CI_COMMIT_SHORT_SHA. build: image: node:latest stage: build variables: CI_COMMIT_SHORT_SHA: "$CI_COMMIT_SHORT_S ...

Automated accounts generated through Javascript and Ajax

To prevent accounts created by bots, I have implemented a simple Javascript function to change the ID of the form: setTimeout(function() { $("#FormAccountCreateTmp").attr("id", "FormAccountCreate"); }, 5400); After 5.4 seconds, the form originally with ...

Utilizing analytics.js independently of the react-ga library

Is there a way to integrate Google Analytics into my React app without using the react-ga package? I specifically want to access the ga function in a separate JavaScript file as well as within a React component. How can I achieve this by importing the anal ...

The use of a MongoId object as an array is not allowed

I am struggling with displaying the values inside a 2D array using echo. It works perfectly fine with print_r: print_r($array); The output is as follows: Array ( [0] => MongoId Object ( [$id] => 57a789b7ce2350b40e000029 ) [1] => MongoId Object ...

Sending data to the server using AJAX with a Django form

I am currently working on implementing a system that allows users to upload both text and a file through my Django form. However, I have encountered an issue where only the message part of the form is being submitted when I try to post it. Even though I ha ...

What is the correct method for verifying if a URL has been generated using the createObjectURL function?

In the scenario I'm facing, users are able to set an image either by providing a URL or by using bytes that are converted into a blob object URL. To prevent resource leaks, it is important to free the blob object URLs when they are changed. However, t ...

Omit certain fields from validation when using $valid in AngularJS

Within my form, I have two select boxes that allow users to move items between them. Let's call them SelectBox1 and SelectBox2. I move all available options from SelectBox1 to SelectBox2. When I try to submit the form, I check for validity. However, i ...

Changing the position of elements dynamically in Javascript by altering their absolute positioning

I am working on an HTML page that contains a div positioned absolutely. My goal is to use Javascript to dynamically move this div downward whenever some data preceding it is generated. I have been experimenting with the .css jQuery function but unfortunate ...

Ways to remove items from an array within an AngularJS program

I'm currently working on a simple task: removing an item from my array. The array is structured as follows: myWordsInJSON = [{"eng":"frau","rus":"жена"},{"eng":"mann","rus":"муж"},{"eng":"witwe","rus":"вдова"},{"eng":"witwer","rus":"в ...

Using Ramda to retrieve objects from an array by comparing them with each element in a separate array

I have two arrays: ids = [1,3,5]; The second array is: items: [ {id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'} ]; I ...

Is it appropriate to invoke componentWillReceiveProps within the componentWillMount lifecycle method?

I'm new to working with react and I have a question. How can I call a function within another function? For example, I want to call componentWillReceiveProps inside of componentWillMount. How can I achieve this? import React from 'react' cl ...

Attempting to decode JSON data

I'm new to node.js and trying to learn how to send a JSON object using REST. However, I keep getting an error message that says "SyntaxError: Unexpected token  in JSON at position 0". I've checked the JSON using an online validator and it seem ...