Search two arrays in a loop and identify variations with a unique approach

Currently, I am facing a challenge that I need assistance with. I am working on an updater that retrieves an XML list of files from a CDN and compares it with an older list to identify any file differences. The objective is to determine which files are out of date and require re-downloading. Unfortunately, I have not been able to find a suitable solution for this issue.

In my current setup, I am using three arrays: Array1, Array2, and DiffArray. Array1 contains the XML entries from the CDN, which can be considered as the master list. Array2 stores the old entries of the files we currently possess, acting as the slave list. Array3 is utilized to store the differences between the two arrays.

Here is a glimpse of the information present in each array. Each new line represents a separate index in the corresponding array:

Array1:

cbt/ar/816.mp3
2019-06-05T16:40:33.212Z
cbt/ar/817.mp3
2019-06-05T16:40:31.509Z
cbt/ar/818.mp3
2019-04-05T16:40:30.978Z
cbt/ar/819.mp3
2019-04-05T16:40:29.807Z

Array2:

cbt/ar/816.mp3
2019-04-05T16:40:33.212Z
cbt/ar/817.mp3
2019-04-05T16:40:31.509Z
cbt/ar/818.mp3
2019-04-05T16:40:30.978Z
cbt/ar/819.mp3
2019-04-05T16:40:29.807Z

A couple of points to note: 1.) This list consists of file names along with their last modified dates. 2.) Array1 includes newer versions of 816.mp3 and 817.mp3 files.

The goal is to compare the file versions, identify the discrepancies, and proceed to download the updated files.

The current code snippet I am using is as follows, but it does not effectively address the issue:

var a = [];
      for (var x = 0; x < remoteArray.length; x++) {
        a[remoteArray[x]] = true;
      }

      for (var y = 0; y < localArray.length; y++) {
        if (a[localArray[y]]) {
          delete a[localArray[y]];
        } else {
          a[localArray[y]] = true;
        }
      }

      for (var z in a) {
        diffArray.push(z);
        log.info("::DIFFERENCES::" + z);
      }

This code snippet only displays the literal differences and does not provide a clear indication of which files require updating.

Answer №1

To simplify the process, consider converting your data into a list of objects that represent each file. While this may not be the most efficient method, it will enhance clarity and ease of maintenance.

function convertToListOfFiles(array) {
    var filesList = [];
    for (var i = 0; i < array.length; i += 2) {
        filesList.push({
            name: array[i],
            modified: array[i + 1]
        });
    }
    return filesList;
}

var remoteFiles = convertToListOfFiles(remoteArray);
var localFiles = convertToListOfFiles(localArray);
var filesToDownload = remoteFiles.filter(file => {
    let match = localFiles.find(localFile => localFile.name === file.name);
    // Download is needed if no local file matches this name or if its modification date is older than the remote one
    return !match || match.modified < file.modified;
});

console.log('Files to be downloaded or re-downloaded', filesToDownload);
// Each file in this list will be represented by an object { name, modified }

If you are unable to utilize features like Array.prototype.filter or arrow functions due to older browsers or Node versions, an alternative method to achieve filesToDownload would be:

var filesToDownload = [];
for (var i = 0; i < remoteFiles.length; i++) {
    var found;
    for (var j = 0; j < localFiles.length; j++) {
        if (remoteFiles[i].name === localFiles[j].name) {
            found = localFiles[j];
            break;
        }
    }
    if (!found || found.modified < remoteFiles[i].modified) {
        filesToDownload.push(found);
    }
}

Answer №2

Here is a snippet of code that helps identify the files that need to be updated by comparing timestamps:

# Creating a dictionary to map each CDN file to its timestamp
cdn_files = {}
for i in range(0, len(Array1), 2):
    cdn_files[Array1[i]] = Array1[i + 1]

# Finding the files that need to be updated
files_to_update = []
for i in range(0, len(Array2), 2):
    file_path = Array2[i]
    # Checking if the file is in the CDN and if the timestamp is newer, then add to update list
    if file_path in cdn_files and cdn_files[file_path] > Array2[i + 1]:
        files_to_update.append(file_path)

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

ASP.NET Core does not support jQuery.validate functionality

After successfully creating a functional jQuery.validation form using HTML, CSS, and JS with dependencies like jQuery and Validation, I encountered an issue when implementing the same code in a clean ASP.NET Core web project. It seems that my custom valida ...

My React App is not displaying the expected Fetch API result

I'm encountering an issue with my react app where I'm trying to fetch an API. Here's the code snippet: import { useEffect, useState } from 'react' export default function Home() { let [ quote, setQuote ] = useState(null) us ...

The dynamics of Express.js functionalities

I am seeking to better understand how flow functions within an Express app using Routes, with the following set of Routes: app.use(require('./routes/reportsRouter')); app.use(require('./routes/crewsRouter')); app.use(require('./ro ...

Array dictionary in PowerShell, is it possible?

I have experience with VBScript where I can create a dictionary and perform lookups like this: Set objDict = CreateObject("Scripting.Dictionary") objDict.Add "item1", Array("data1", "data2") objDict.Add "item2", Array("data3", "data4") Then I can retriev ...

Guide to embed a Google Sheets chart into a WordPress website

I'm looking to include a chart in a wordpress post, using the script generated from google sheets' publish function. When I add the script to a generic HTML page, the chart displays properly. However, when I insert it into a wordpress post, I en ...

What is the indicator that signals a change in the value of a React ref.current?

Typically, when using props, we would write componentDidUpdate(oldProps) { if (oldProps.foo !== this.props.foo) { console.log('foo prop changed') } } to identify any changes in props. However, if we utilize React.createRef(), how can w ...

The play button in the customized React AudioPlayer may sometimes need to be tapped twice in order to start

I've encountered an issue with my simple audio player (React/Vite) that transitions to the next track automatically or manually. Everything seems to be functioning correctly except for the initial press of the play button. The player opens with the pa ...

Tips for successfully passing an object via a Link

I am trying to pass an object through a Link component in react-router v6. Can someone please guide me on how to achieve this? Below is a snippet of my code where the user should be directed to another component. import React from 'react' import ...

Can applications on Windows 8 operate using JavaScript, HTML5, and CSS3 that adhere to industry standards?

As a .NET developer, I tuned in to the keynote for the Build Event in Anaheim, California and had some questions regarding the new support for creating Windows 8 applications using JavaScript, HTML5, and CSS3. They showcased several examples and mentioned ...

Error: The property 'setCrossOrigin' is not defined and cannot be read

When I try to run both .obj and .mtl files together, I encounter an error, whereas running just the .obj loader works fine. The specific error message that appears is: MTLLoader error Below is the code snippet I am using to load the .obj and .mtl files: ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

Combining arrays encoded in JSON format

Consider the following array examples: $array1 = [ 'test' => json_encode([ 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' ]) ] Now, let's ...

Keystrokes may not consistently register in Firefox

I created a compact web application where users can interact by clicking on a button to trigger a modal dialog. Within this dialog, users have the ability to choose from various options. To enhance user experience, I implemented the utilization of the jQue ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

Focusing solely on a particular category in EJS

I am struggling with this code snippet. HTML: <header<% if ( current.source === 'features' || current.path[0] === 'index' || current.source !== 'customers' ) { %> class="header-white"<% } %>> <div cl ...

The onClick function is called when I fail to click the button within a React form

I set up a form and I would like to have 2 ways to submit it: One by filling out the input field and pressing enter One by recording voice (using the react-speech-recognition library) However, after adding the second way, the input fi ...

Is Meteor.js the solution for time-triggered server requests?

We are currently in the process of developing an application that matches users from a database every Wednesday and Friday. How can we achieve this using Meteor? In the server code, I am considering organizing this functionality within a timedserver.js fi ...

Working with ReactJS, Material-UI, and Javascript: Facing challenges in applying rounded borders to TableRow components

I've been trying to achieve rounded borders on a TableRow element, but adding the style "borderRadius: 5" doesn't seem to have any effect. When I try wrapping the TableRow in a Box element with borderRadius, it does make the borders rounded but m ...

What happens if I don't associate a function or method in the React class component?

Take a look at this straightforward code snippet that updates a count using two buttons with different values. import "./App.css"; import React, { Component } from "react"; class App extends React.Component { // Initializing state ...

Is it possible to include all visible content, even when scrolling, within the full page height?

My webpage contains content that exceeds the height of the window. I am looking for a way to retrieve the full height of my page using either jQuery or pure Javascript. Can anyone provide a solution? I have considered the following approach: $('body ...