Ensure that there are no duplicate values across various fields within an array of objects by using a specific condition in JavaScript

Given an array of objects, determine if there are any duplicates based on certain conditions in JavaScript.

The following conditions need to be checked:

  • If the object with type 'local' has a duplicate code, return true
  • If the object with type 'IN' or 'IN Travel' has a duplicate code, return false
  • If there are objects with the same type 'IN' and the same code, return true
  • If there are objects with the same type 'IN Travel' and the same code, return true
var objarray1=[
  {id:1, name: "ram", code: "NIXZ", type: "Local"},
  {id:2, name: "abey", code: "ABCN", type: "IN"},
  {id:3, name: "jaz", code: "ABCN", type: "IN Travel"}
]

Expected Result 
// since type-IN or IN travel and code has duplicate
false

// The existing code does not fulfil the above conditions
function checkArrayObject(arrobj){
   
  const getLocal = arrobj.filter(e=>e.type=="local");
  const checklocalcode = arrobj.filter(e=>e.type=="local").map(i=>i.code);

  const getIN = arrobj.filter(e=>e.type=="IN");
  const checkINcode = arrobj.filter(e=>e.type=="IN").map(i=>i.code);
  
  var result;
  arrobj.forEach(e=>{
    if(getLocal.length === checklocalcode.length) {
      result = true;
    } else {
      result = false;
    }
    if(getIN.length === checkINcode.length){
      result = true;
    } else {
      result = false;
    }
   });
   
   return result;
}

Answer №1

function checkDuplicateCodes(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (i !== j && arr[i].code === arr[j].code) {
        return false;
      }
    }
  }
  return true;
}

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

Utilize buttons to send data to a PHP script

Currently, I am in the process of developing a control panel for an application, consisting of an array of buttons. My aim is to relay information about the specific button pressed to the designated script responsible for executing commands. However, I am ...

When the PHP function is invoked from JavaScript, no results are displayed

I need assistance with calling a PHP function from JavaScript. The goal is to call the PHP function and have it echo two arguments that are passed. However, the code I have written does not seem to be working as expected, as it does not print anything. Ca ...

Encountering an error in Angular where the property 'nativeElement' is undefined when using @ViewChild

I have a div in my code named #map that will be displayed after a certain condition is met in a for loop. <div *ngFor="let message of fullMessagesArr"> <div *ngIf="message.replyMap"> <div #gmap style="width:100px;height:400px"></d ...

Understanding variable scopes in the success callback function of a JQuery post request

I am encountering an issue with passing the AJAX success array from one function to another. It seems that I am unable to transfer the data stored in a variable within the success section of the AJAX function to the parent function for return. I tried to ...

Issue with .click() function in JQuery not functioning

My View has a map with markers that display pop-ups when clicked, which is functioning correctly. Below is the code for the map functionality: export function all_hotels_map_results(): void { Helpers.set_currency_settings(); const json = gon.hot ...

"Develop an interactive feature with jQuery that dynamically generates and removes fields according to the option selected from a

Can someone provide suggestions on how to achieve the functionality of adding and deleting input fields based on a user's selection from a drop-down menu using jQuery? I have successfully added the input fields, but I'm facing some confusion rega ...

NavigAuth - NativeScript Vue's Innovative Authentication-driven Navigation

After spending hours trying to figure this out, I need to ask for help. How can I create a simple Auth-based Navigation within my App? I have successfully set up a Firebase auth user inside my Vuex using an auth listener. Now, all I want is to display th ...

Unable to send back array after validation in Laravel 5.3 results in an error

I am facing an issue with my view: <input type="text" name="color[]" value="{{ old('color') }}" placeholder="Enter Color"> <input type="text" name="price[]" value="{{ old('price') }}" placeholder="Enter Price"> Since color ...

Tips on inserting table data into a textarea input using a button

Is there a way to display the text from the table in a textarea box when clicking the "add" button, without removing the data once it's added? I simply want the text "Add this text to textarea" to show up in the textarea box. https://jsfiddle.net/bj ...

Tips for customizing Material UI Tooltip styles

Is there a way to customize the appearance of the Material UI Tooltip title? I have noticed that by default, the tooltip displays with a black background and no text wrap on hover. Can the background color, text color, and other styles be modified? Wonde ...

Dispatch is functioning properly, however the state remains unchanged

I'm currently developing an application that utilizes redux for state management. In a particular scenario, I need to update the state. Here is how my initial state and reducer function are set up: import { createSlice } from '@reduxjs/toolkit&a ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

Ways to implement a percentage for scrollTop

I'm currently troubleshooting the code below. My goal is to understand why I'm unable to scroll the .post div with jQuery and input range properly using a percentage value like this: $("[type=range]").on('input',function(){ var v ...

Arranging squares in a circular formation with Three.js

I am facing an issue with aligning squares within a circular grid to its center. Despite the correct center point, the entire grid is consistently skewed to the right. The problem could be due to incorrect calculations for removing squares outside the cir ...

Prevent memory leakage by utilizing Angular's $interval feature in countdown processes

I have a controller set up to handle a countdown feature: var addzero; addzero = function(number) { if (number < 10) { return '0' + number; } return number; }; angular.module('theapp').controller('TematicCountdownCo ...

Creating an express route for updating with various parameters: a step-by-step guide

I am trying to make an update to a specific attribute in a JSON object by using the fetch PUT method. I have set up a put function that takes in 2 URL parameters app.put('/trustRoutes/:id/:item', (req, res){ So far, I have been able to update t ...

Exploring different categories within WordPress

I have a variety of products that will be sorted into different categories when selected. My goal is to display specific images based on the categories that are clicked. For example: If I click category A, then image (A) should appear. Below is the cod ...

"AngularJS directive mandating the use of the required attribute for internal control

I've encountered a challenge with this specific issue. We are using a directive called deeplink, which contains the following code: restrict: 'E', require: 'ngModel', scope: { smDropdown: '=smDeeplinkDropdown', s ...

Checkbox selection and display: Check the box to reveal its value in a div, along with a close button for

While following a tutorial, I came across a scenario where multiple checkboxes are involved. Upon selecting the checkbox and clicking on the "get selected value" button, the value of the selected checkboxes is alerted. However, I would like to make a mod ...

The method 'push' is not compatible with this object

While working with AngularJS, I encountered an issue when trying to insert a new value into an existing JSON object. The error message I received was: "Object doesn't support property or method 'push'" Below is the code snippet I am using: ...