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

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

Assign a class to the following element using an Angular 2 Directive

I have a dropdown menu and I want to incorporate an Angular2 directive to control the opening and closing of this dropdown. How can I apply the open class to the latest-notification div, knowing that my directive is applied to the button tag? Below is my ...

I encountered an error while trying to load the resource from http://premieroptie.nl/wp-content/themes/theme51771/favicon.ico: net::ERR_NAME_NOT_RESOLVED

Upon opening my website URL, computertechnet.nl, I noticed an error when inspecting and checking the console tab. The specific error message is: Failed to load resource: net::ERR_NAME_NOT_RESOLVED for . In addition, a second warning was displayed: G ...

Methods for transferring data from an AJAX function

I have a database containing various links that I would like to retrieve and store within an array. I attempted to achieve this using the following code: var amz = new Array(); function CreateAmazonArray() { $.ajax({ url: "php/amazon_affilia ...

tag-swapping function

I have a specific HTML code paragraph that I am working with: <p id=tag1> html statements before click </p> My goal is to create a function that will split the paragraph into two separate paragraphs like so : <p id=tag1> html statement ...

Generate a vector3 with a defined direction

I have a challenge at hand where I am looking to create a 2D flow field in three.js based on a working example I found in p5.js. The original source code for reference is as follows: var inc = 0.1; //Increment of noise var yoff = 0; var scl = var; //Scale ...

Is it possible to hide a fixed header on scroll in a mobile device?

I am facing an issue with my Wordpress site where I want the header to hide when the user scrolls. Despite trying various codes, I have been unable to make it work. The reason for wanting to hide the header is that on mobile devices, it causes scroll prob ...

Does __ only function with curried functions as intended? What is the reason for it working in this case?

I'm trying to figure out the reason behind the successful usage of __ in this particular code snippet : function editAddress (id, addressId, model) { return BusinessService .getById(id) .then(unless( () => checkUrlValue(add ...

The lack of intellisense in VS Code for Node.js poses a significant challenge for developers

I am facing a problem with IntelliSense in Visual Studio Code. Despite installing multiple extensions, it is not working as expected. The IntelliSense feature only shows functions and variables that have already been used in my code file. Below is the li ...

How can Angular 2 populate forms with data retrieved from a promise in a database?

I'm currently navigating through the world of Angular and Firebase, and I’ve hit a roadblock when it comes to populating my forms with data from Firebase promises. Understanding how to work with promises versus observables is also proving to be a ch ...

Using arrays to create visual Google charts

I am attempting to pass an array of numbers to a Google chart by extracting the array from a div with the class .likescount. var i, $mvar = $('.likescount'); function logit( string ) { var text = document.createTextNode( string ); $(&a ...

Angular attribute directive accesses a sibling attribute reference

Attempting to create an attribute directive named pagingContext that will work alongside the angular material sort directive matSort. The concept is to have an element structured like: <table matSort [pagingContext]="pagingContext"> With a directi ...

Modifying webpack settings for a create-react-app based project: A step-by-step guide

After starting a new react project with create-react-app, I am looking to update the webpack configuration. However, I cannot seem to locate the webpack file. Should I be creating this file myself, or is there another process involved? As someone who is ...

In WordPress, the magic_quotes feature is essential for json_decode to function properly

In my current project on the client side, I am dealing with an array of JavaScript objects. Upon submission, this array needs to be sent to PHP using a form and then further manipulated on the server-side. As I work on building or modifying the array of o ...

Tips for updating content (wishlist) without the need to refresh the page

Currently experimenting with the TMDb API to enhance my PHP skills. I've successfully created a wishlist feature and now looking to optimize the script. A function is implemented on each movie page for adding movies to the wishlist. function getButt ...

Unable to display texture and color on .obj files in Three.js

After introducing a new model in .obj and .mtl formats into my three.js code, I encountered an issue where the color of the model would turn white, regardless of its original color or texture. Below is a snippet of the code related to the pig model: // ...

Sending JSON data to the server using jqGrid: A step-by-step guide

[CHANGE] (I couldn't bear to wait 3 hours for an answer): It seems that the issue is not with the jqGrid component, many thanks to TheCodeDestroyer for identifying this. I ran this code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "h ...

Issue with noUnusedLocals flag detection within function* block

Compiler options: "noUnusedLocals": true, "noUnusedParameters": true, are not functioning properly within functions. An error is encountered in the following example: export class AllReduxSagas { [ts] Property 'someService' is declared bu ...

Error: Unable to access the 'offsetTop' property of null

I attempted to implement a scroll effect in my project. The goal was for users to be taken to a specific section when they clicked on an option in the navbar. However, I encountered an error during implementation. Below is the code snippet where the error ...