javascript identify dissimilarities within arrays

Working on an Angular 2 application and attempting to identify the difference between two arrays (last seven days and missing dates within the last seven days). Everything works fine when initializing the array through a string, like in example code 1. However, there seems to be an issue when retrieving data from the database.

var array1 = ['20180605', '20180606', '20180607', '20180608', '20180609', '20180610', '20180611']
var array2 = ['20180606', '20180607', '20180608']
var ind

for (var i = 0; i < array2.length; i++) {
  ind = array1.indexOf(array2[i])
  if (ind > -1) {
    array1.splice(ind, 1)
  }
}
console.log('diff', array1)

However, the method above is not performing as expected.

let datas = [
  {'dateString': '20180607'},
  {'dateString': '20180606'},
  {'dateString': '20180608'}
]

let originalDataArray = []
for (let data of datas) {
  originalDataArray.push(data.dateString)
}

let dataArray = []

function formatDate (subtractDate) {
  let datestring
  datestring = moment().subtract(6 - subtractDate, 'days').format('YYYY' + 'MM' + 'DD')
  dataArray.push(datestring)
}

let lastSevenDaysArray = []
for (let i = 0; i < 7; i++) {
  let date = formatDate(i)
}

var array1 = originalDataArray
var array2 = dataArray

var ind

for (var i = 0; i < array2.length; i++) {
  ind = array1.indexOf(array2[i])
  if (ind > -1) {
    array1.splice(ind, 1)
  }
}

console.log('diff', array1)

Answer №1

You seem to have mixed up array1 and array2. The corrected code should look like this:

for (var i = 0; i < array1.length; i++) {
  ind = array2.indexOf(array1[i])
  if (ind > -1) {
     array2.splice(ind, 1)
  }
}
console.log('diff', array1);

Furthermore, I recommend optimizing your code as shown below:

let datas = [{'dateString': '20180607'},{'dateString': '20180606'},{'dateString': '20180608'}];

let originalDataArray = datas.map(({dateString}) => dateString);

let dataArray = []
for (let i = 0; i < 7; i++) {
  dataArray.push(formatDate(i));
}

function formatDate (subtractDate) {
  return moment().subtract(6 - subtractDate, 'days').format('YYYY' + 'MM' + 'DD')
}
dataArray = dataArray.filter(c => !originalDataArray.includes(c));

console.log('diff', dataArray)

Answer №2

When working with two arrays of different lengths, there is a more straightforward way to identify the variance:

const array1 = ['20180605', '20180606', '20180607', '20180608', '20180609', '20180610', '20180611'];
const array2 = ['20180606', '20180607', '20180608'];

for (let el of array2) {
  if (array1.includes(el)) {
    array1.splice(array1.indexOf(el), 1);
  }
}

console.log(array1);

This process eliminates the overlapping elements from array2 in array1, resulting in only the exclusive elements that are not present in array2.

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

Create a dedicated component to specify the column definition for an Angular Material table

While I have reviewed the documentation on material, I aim to take it a step further with the following customization: wrapper-table.html <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-content>& ...

Mastering the art of passing and translating languages through selected options in different components using ngx-translate

Currently, I am utilizing the ngx-translate library for localization within a specific component and it is functioning correctly. Here's the setup: I have designed a language selection dropdown component that is being used in the Login component witho ...

What could be causing the .env.development file to malfunction in my Next.js application?

I am currently working on Jest and testing library tests. Let's discuss a component named BenchmarksPage. Please pay attention to the first line in its return statement. import { Box, capitalize, Container, FormControl, InputLabel, MenuI ...

Angular template driven forms fail to bind to model data

In an attempt to connect the model in angular template-driven forms, I have created a model class and utilized it to fill the input field. HTML: <div class="form-group col-md-2 col-12" [class.text-danger]="nameCode.invalid && nameCode.touched ...

Acquiring and resetting Angular states: A beginner's guide

I'm facing a situation where I need to perform a route jump (essentially a refresh) on the same page, but this jump includes state data. However, even though the state contains valuable information, I am only able to access it through history and cann ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...

Express is throwing a TypeError because it is unable to access the property 'app', which is undefined

On my nodejs server running the express framework, I have been encountering a random error when making requests. The error occurs unpredictably, usually appearing on the first request and not on subsequent ones. It's challenging for me to identify the ...

Tips for retrieving sent data from a jQuery Ajax request on XHR error

I am facing a situation where I have numerous jQuery AJAX requests being sent using a single function. function sendData(data){ $.post("somepage", {"data": data}, function() {}, "json") .fail(function(jqXHR, textStatus, errorThrown){ sendD ...

Enter a socket.IO chat room upon accessing an Express route

Encountering difficulty when attempting to connect to a socket.IO room while accessing a specific route in my Express application. The current setup is as follows: app.js var express = require('express'); var app = express(); var http = requir ...

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

Struggling to reflect changes in the database using the updated value in the localStorage

I have a table where the td is set to contenteditable. To update the value of the td in my database, I decided to use localStorage. When the save button is clicked, the inputted value in the td will be saved to localStorage and retrieved via AJAX to replac ...

Transforming the window property in distinct entry points for TypeScript

During the initial page load, I am looking to transfer data from a template to a TypeScript file by attaching it to the window object. I want each page to utilize the same variable name for its specific data (window.data). An example of this can be seen in ...

Rendering Highcharts React Pie Chart Multiple Times

Here is the code snippet: import React, { useEffect, useRef, useState } from "react"; import * as Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; export const PieChart = (props: any) =&g ...

Is there a Problem with Paging in Meteor with Jquery?

I implemented Pagination using Jquery, but I encountered an issue along with the following error message: Uncaught TypeError: Object [object Object] has no method 'customPaginate' I am unsure how to resolve this problem. Could you please take ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...

Troubleshooting npm test failure on CircleCI due to inability to locate installed package

It's puzzling that Circle is encountering issues with utilizing ts-mocha after it was successfully installed with npm install in a previous step of the build process. The functionality used to function properly, but now it suddenly stopped working. ...

The Angular-ui typeahead feature is delivering accurate results when the backspace key is pressed

I've been using Angular-UI typeahead and it's been working fine, but I've noticed a strange behavior when I hit the backspace key - it gives the correct results. For example, if I type sector 4 The result is Sector 1 Sector 2 ...

Are none of the page links clickable?

Currently, I am in the process of creating a portfolio website. This is my first attempt at coding HTML and CSS from scratch without the aid of a layout template. I've encountered an issue that has me stumped - the links within the container are not ...

Data entered into DynamoDb using typedORM displays inaccurate Entity details

Whenever I add new entries to my local dynamoDb table using typeDORM within a lambda function, it seems to save the record with the incorrect entity information. For example, the GSI1PK GSI1: { partitionKey: 'PRO#{{primary_key}}', ...