Using JavaScript to compare arrays in order to display only the distinct outcome

Just starting out with JavaScript array matching!

I've got two arrays, both with 11 elements each:

txtfilename=['txt1','txt6','txt6','txt6','txt7','txt7','txt8','txt9','txt9','txt9','txt9']
content=['apple from one','six trees','cats','happy dogs','healthy fruit','good job','ask question','check safety','stay in the house','good results','happy holiday']

The position of elements in txtfilename matches the position of elements in content.

For example: the 2nd element in txtfilename corresponds to the 2nd element in content.

However, txtfilename has duplicate elements while content is unique.

I'm struggling to match these arrays and would like to display them as follows:

txtfilename: txt1
content: apple from one

txtfilename: txt6
content: 'six trees', 'cats', 'happy dogs'

txtfilename: txt7
content: 'healthy fruit', 'good job'

txtfilename: txt8
content: 'ask question'

txtfilename: txt9
content: 'check safety', 'stay in the house', 'good results', 'happy holiday'

Answer №1

    //Creating arrays
    String[] filenames = new String[] {"file1", "file6", "file6", "file6", "file7", "file7", "file8",
            "file9", "file9", "file9", "file9"};

    String[] dataContent = new String[] {"apple from one", "six trees", "cats", "happy dogs",
            "healthy fruit", "good job", "ask question", "check safety", "stay in the house",
            "good results", "happy holiday"};

    //Building a map
    Map<String, String> fileDataMap = new HashMap<>();

    //Iterating through the arrays
    for (int j = 0; j < filenames.length; j++) {

        //Checking if the map contains the filename
        if (fileDataMap.containsKey(filenames[j])) {

            //Appending new content to existing content in map
            //For example: file6, file7 and file9
            StringBuilder value = new StringBuilder(fileDataMap.get(filenames[j]));
            value.append(", ");
            value.append(dataContent[j]);
            fileDataMap.put(filenames[j], value.toString());
        } else {
            //Adding filename and content to map
            fileDataMap.put(filenames[j], dataContent[j]);
        }

    }

    // Displaying contents of map
    for (Entry<String, String> entry : fileDataMap.entrySet()) {
        System.out.println("Filename: " + entry.getKey());
        System.out.println("Content: " + entry.getValue());
        System.out.println();
    }

This code snippet should get the job done

Answer №2

One way to utilize a MapReduce algorithm in JavaScript is as follows:

var results = fileNames.map((item, index) => ({"fileName": item, "content": contents[index]}));
var shift = 0;
fileNames.forEach((item, index, arr) => {
   if (index < arr.length - 1 && item === arr[index+1])
   {
       results[index + shift].content += ", " + contents[index+1];
       results.splice(index + 1 + shift, 1);
       shift--;
   }
});
console.log(results);
// Output will display merged objects where fileName matches 

Edit :
Initially, I map file names and their corresponding content to create an array of objects with properties for fileName and content.
Then, by comparing each object with its neighbor (as the array is sorted by fileName), if two adjacent objects share the same key (fileName property), I combine their content strings into the first object and remove the now redundant second object.

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

The Nuxt.js authentication module remains in place and does not redirect users who are already logged

An authenticated user can still access the /login page. If I click on a link to the /login page, I am redirected to a different page successfully. However, if I manually type in /login in the URL, I am still taken to the login page even though I am already ...

What is the best way to retrieve EXIF data following the AJAX loading of images?

Currently, I am developing a swipe-able wine image viewer for NapaWapa.com and it's functioning quite smoothly: The challenge I'm facing is related to using a jquery plugin to extract the exif data from the images in the gallery. Unfortunately, ...

A guide to sending multiple data using Ajax or Json in Javascript

Sorry for my confusion, but I'm unsure if this involves AJAX or JSON as I am not proficient in this language. However, my issue pertains to sending values from two listboxes: the year and the month. The year is being sent to data-basic-colm-ajax.php, ...

Take away the attention from the span element

I have been experimenting with the following jsfiddle and attempted various methods suggested in this Stack Overflow thread, but I am struggling to remove the focus from the "feedback" span after clicking on the cancel button in jQuery confirm dialog. Her ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

Issues with Google Fonts failing to load correctly

Would you mind taking a look at this issue for me? In all browsers except Firefox, the expected behavior is that a web font remains invisible until fully loaded, preserving space on the page. Interestingly, in Chrome and IE9 (the browsers I tested), ther ...

Tips for concealing JavaScript code while inspecting elements with AngularJS

Is it possible to display minified JavaScript code when using Angular and inspecting elements? ...

The defaultLocale setting in Next.js i18n is failing to retain the default language

I am currently working on setting my default language in Next.js i18n, but I keep encountering a problem where "En" is always set as the default language, acting as a fallback. Additionally, I am receiving this error message: Error: [@formatjs/intl Erro ...

Tips for postponing a function's execution in order to ensure it has completely loaded

I am facing an issue with a dynamic page that is populated by an ajax call. Here is the current code snippet: function loadPage() { var container = document.querySelector(".container"); var xhr = new XMLHttpRequest(); xhr.open('GET ...

What is the best way to switch image position using javascript?

I'm experimenting with creating a function that toggles the image source when clicked - changing it back and forth. <img src="http://images.clipartpanda.com/laughing-smiley-face-clip-art-smiley-face-clip-art10.jpeg" longdesc="http://sm ...

Tips for synchronizing text field and formula field content on MathQuill 0.10

I am currently working on creating a WYSIWYGish input element for my formula, along with a LaTeX input element. <span id="editable-math" class="mathquill-editable"></span> The goal is to make these two elements work synchronously. Here's ...

Price Adjuster Tracker

Recently, I coded a small JavaScript program with the purpose of: incrementing or decrementing the quantity of an item by 1 adjusting the price of an item based on the initial price However, my excitement turned to disappointment when I encountered these ...

What could be causing me to receive two builds when using Webpack?

I am trying to capture the hash of the build by using a callback function in webpack: const compiler = webpack(webpackConfig, function (err, stats) { debug("Hash", stats.hash) }) However, I am encountering an issue where two builds are generated and on ...

Retrieve key-value pairs from a database and store them as variables in PHP before transferring them into an array in JavaScript

My challenge lies in loading Chinese characters as keys and their English translations as values from a database into a PHP array, so that I can use them on the client side in JavaScript. The process involves fetching key:value pairs from PHP into a JavaSc ...

Prevent the display of hyperlinks in the status bar when hovering over a hyperlink or button

The application I'm working on has a default status bar at the bottom of each screen that displays URLs linked to buttons and icons. For example: https://i.stack.imgur.com/ZFTsp.jpg I am trying to prevent the display of URLs associated with hyperlin ...

One can only iterate through the type 'HTMLCollection' by utilizing the '--downlevelIteration' flag or setting a '--target' of 'es2015' or above

I'm currently working on developing a loader for my static grid. I've incorporated the react-shimmer-skeleton package source code, but I'm encountering issues with eslint in strict mode. You can find the respective repository file by followi ...

Is it considered best practice to call the same function within itself in a function?

function takeANumber() { let startHealth = parseInt(prompt("Please enter a positive number:")); // I am recursively calling the same function within an if block to ensure that the input is a valid number greater than zero. Is this considered good practic ...

The search feature on mobile devices is currently malfunctioning

The jQuery code below is used to search for products. It works perfectly in desktop view, but the responsive mobile view does not seem to be functioning correctly. Can someone assist me with fixing this issue? $("#search-criteria").keyup(function() { ...

Differences between Vue.js onMounted and watching refsVue.js offers

When it comes to calling a function that requires an HTMLElement as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting ...