Removing duplicate elements from an array prior to adding them to the array

I have an array of values as shown below

var inputValues = ["java","php","python"] //values from user

var responseValues = [{"name":"mysql"}, {"name":"golang"}, {"name":"svelte"}] //response from JSON

I need to compare the input array with the existing data in the response JSON before inserting the input array.

If all the values in the input array match any value in the response array, an alert will be shown using JavaScript. If none of the values in the input array matches with any value in the response array, all the values from the input array will be inserted.

I have successfully created a code to insert the array using $.each.

I would like to know how to filter and check the input values against the response JSON data before performing the insertion.

Below is the code I am currently using to insert the array

  var counter = 0;
  var totalInputs = inputValues.length;
  $.each(inputValues, function (index, value) {
    $.ajax({
      url:"<?= base_url();?>controller/function",
      type:"POST",
      dataType:"json",
      data:{"name":value},
      success: function(response){
        counter++;
        if (counter == totalInputs)
        {
            setTimeout(() => {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    timer: 1500,
                    showConfirmButton: false
                }).then((result) => {
                    location.reload();
                });
            }, 500);
            
          }
        }
     })
   }) 

Answer №1

You have the option to utilize array.prorotype.some():

This scenario includes duplicates of mysql and golang:

let name = ["java","php","python","mysql","golang"]; //received from user
var res = [{"name":"mysql"}, {"name":"golang"}, {"name":"svelte"}]; //response retrieved from JSON

let duplicates = [];

name.forEach(function(item) {
  if(res.some(elem => elem.name === item))
    duplicates.push(item);
});

if(duplicates.length > 0) {
  alert("The user array contains duplicates:\n " + duplicates);
} else {
  name.forEach(function(item) {
    res.push({"name": item});
  });
}

console.log(res);

No duplicates present:

let name = ["java","php","python"]; //input received from user
var res = [{"name":"mysql"}, {"name":"golang"}, {"name":"svelte"}]; //JSON response data

let duplicates = [];

name.forEach(function(item) {
  if(res.some(elem => elem.name === item))
    duplicates.push(item);
});

if(duplicates.length > 0) {
  alert("The user array contains duplicates:\n " + duplicates);
} else {
  name.forEach(function(item) {
    res.push({"name": item});
  });
}

console.log(res);

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

I don't understand why I keep encountering a "segmentation fault 11" even though I have allocated sufficient memory

I am working on a double pointer char array to store strings, implementing an append function. The goal is to add a provided string to the end of the array while keeping track of the number of elements using num_strings pointer. However, I am facing an iss ...

Utilize Typescript to aim for the most recent edition of EcmaScript

Are you looking to configure your typescript build to compile to the most recent version or the most current stable release of EcmaScript? For example, using this command: tsc --target <get latest version> Alternatively, in a tsconfig file: { & ...

Show search results in real-time as you type

I am currently developing a SharePoint 2007 web part using Visual Studio. The main goal of this web part is to search a SharePoint list and present the results to the user. My objective is to have the results displayed automatically once the user finishes ...

Is there a way to retrieve the width of the parent element in ReactJS from a child component?

The issue has been fixed: I forgot to include .current in my ref... I am trying to determine the width of the element that will hold my component. I came across a solution on SO, but unfortunately it did not work for me as it returned undefined: import R ...

Is there a way to display the specific information of a flatlist item in a pop-up window?

Welcome to the HomesScreen.js! This section handles rendering the flat list elements. import { StatusBar } from 'expo-status-bar'; import { Button, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import { ...

Decoding JavaScript elements embedded in an HTML website

My current HTML site includes the following code: <script type="text/javascript"> jwplayer('player_container').setup( { 'width': '640', ...

Troubleshooting Media Queries Problems in HTML and CSS

Check out the code snippet below: //Modifying text content (function() { var texts = $(".altered"); var textIndex = -1; function displayNextText() { ++textIndex; var t = texts.eq(textIndex) .fadeIn(2000) if (textIndex < te ...

Exploring ways to retrieve global variables within a required() file in Node.js

Imagine having 2 files: main.js, and module.js: //main.js const myModule = require('./module'); let A = 'a'; myModule.log(); //module.js module.exports = { log() { console.log(A); } } After trying to call myModule.log, ...

When trying to access an array directly within an object, it all too often returns as undefined

There is a React Component that has been provided with an array of objects (main_object), one of which contains another array of objects (secondary_object). Strangely, when trying to print the main object in console.log, the array is visible, but attemptin ...

Retrieving information from the API to populate a child component in Next.js

I have been developing a header component and here's the code snippet: import style from '../../styles/header.css'; import '../../styles/globals.css'; export default function Header({data}){ const [showMe, setShowMe] = useStat ...

The best jQuery method for parsing through an array of JSON objects

Storing a JSON array in local storage can be achieved by creating JavaScript objects. For example, we have item1 with item_id 332443, item_rank 3.6, and item_type BMW, Camry, Ford. var item1 = { item_id:332443, item_rank:3.6, i ...

What is the best way to ensure that a collection is only released when necessary?

Within my application, I have a streamlined public profile that showcases only a portion of the fields stored in my Meteor.users collection. While I understand that I can selectively publish specific fields from the collection, I am concerned about unnec ...

Issues arising during the initialization of Tinymce

After setting the editor on the frontend, I encountered an issue with initializing tinymce. Here is my code: <head> <script src="//cdn.tinymce.com/4/tinymce.min.js"></script> </head> <body> <a class=pageedit>Edit< ...

Is this preloader code actually preloading something?

Struggling to add a preloader on my website. I came across the following code that appears to be functioning (I can see the CSS animation before the images load - check out this JSFiddle). However, I'm unsure about how the JS code actually operates... ...

modify header when button is clicked

I am trying to create a JavaScript function that will update the name of an HTML table header when a button is clicked. However, I am having trouble accessing the text content within the th element. document.getElementById("id").text and document.getEl ...

Guide on incorporating bold and unbold features using AngularJS

I'm currently working on implementing client-side text formatting functionality that resembles what a typical editor does. Essentially, when a user selects text and clicks on the "bold" button, it should apply bold formatting to the selected text. Cli ...

The success of a jquery ajax call always seems to elude me as it consistently throws

I've been facing an issue with my code snippet. The problem lies in the fact that the function on success is never executed; instead, it always triggers the error section. $.ajax({ url: 'http://localhost/zd/get_list', data: 'ter ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Tips for displaying PHP form data dynamically in a responsive Bootstrap modal when clicking on it

I have successfully implemented PHP and HTML code to retrieve data (text and images) from a database. Now, I am looking to enhance the user experience by having the images open in a modal (bootstrap lightbox) when clicked, displaying further details along ...

What could be causing the React variable to malfunction within my state object?

class ColoredSquares extends React.Component { constructor() { super(); this.selectedColor = 'green'; } state = { backgroundColor: this.selectedColor, width: "50px", height: "50p ...