Creating a function to filter an array of objects based on specific properties and values in JavaScript

How can you compare arrays of objects with arrays using JavaScript?

I am looking to evaluate an array of objects based on specific conditions.

  1. If the targetvalue is the same and the code value is not present in the arraylist, return the array of objects.

  2. Otherwise, if the targetvalue is the same and the code has the same value in the arraylist, return the array of objects.

Otherwise, return an empty array []

var arraylist =["IT","FI"];
var arrobj1 =[
  {id:1, name: "sonu", code: "IT", targetvalue: "908"},
  {id:2, name: "abi", code: "IT", targetvalue: "834"},
  {id:3, name: "lisa", code: "SP", targetvalue: "834"},
  {id:4, name: "ben", code: "FI", targetvalue: "234"},
]

Expected Output 
//same value, and includes `IT` 
[]

****

var arrobj2 =[
  {id:1, name: "sonu", code: "IT", targetvalue: "908"},
  {id:2, name: "abi", code: "IT", targetvalue: "834"},
  {id:3, name: "lisa", code: "SG", targetvalue: "234"},
  {id:4, name: "ben", code: "SP", targetvalue: "234"},
]

Expected Output
//same targetvalue and not included `FI or IT`, so return
[
 {id:3, name: "lisa", code: "SG", targetvalue: "234"},
  {id:4, name: "ben", code: "SP", targetvalue: "234"},
] 


****

var arrobj3 =[
  {id:1, name: "sonu", code: "IT", targetvalue: "908"},
  {id:3, name: "lisa", code: "FI", targetvalue: "234"},
  {id:4, name: "ben", code: "FI", targetvalue: "234"},
]
Expected Output
// targetvalue and code are the same
 [ {id:3, name: "lisa", code: "FI", targetvalue: "234"},
  {id:4, name: "ben", code: "FI", targetvalue: "234"}]

I have attempted to use the following code for this comparison:

const checkIdList = list => {
    const idlist = ['IN', 'FI'];
    const resultarray = list
      .map((obj, i) => list.find((elem, index) => {
        if (i !== index && elem.targetvalue === obj.targetvalue && 
           (element.code === obj.code || idlist.includes(element.code))) {
          return obj;
        }
      }))
      .filter(x => x);
    return resultarray;
  };
var finalResult = this.checkIdList(arrobj1);
  
  

Answer №1

To begin, you should first group the elements based on their targetValue. After that, apply a filter to the resulting Object.values considering three specific conditions:

function checkIdList(array, list) {
  // Grouping by targetValue
  const grouped = {};
  for (const o of array) {
    (grouped[o.targetvalue] ??= []).push(o);
  }

  return Object.values(grouped)
    .filter(g =>
      g.length > 1 // Subarrays with length greater than one indicate duplicates
      && (
        g.every(({ code }) => !list.includes(code)) || // Include if every code is not in the list
        g.every(({ code }, _, a) => code === a[0].code) // OR include if all codes are equal and present in the list
      ))
    .flat();
}

const arraylist = ["IT", "FI"];
const arrobj1 = [{ id: 1, name: "sonu", code: "IT", targetvalue: "908" }, { id: 2, name: "abi", code: "IT", targetvalue: "834" }, { id: 3, name: "lisa", code: "SP", targetvalue: "834" }, { id: 4, name: "ben", code: "FI", targetvalue: "234" },];
const arrobj2 = [{ id: 1, name: "sonu", code: "IT", targetvalue: "908" }, { id: 2, name: "abi", code: "IT", targetvalue: "834" }, { id: 3, name: "lisa", code: "SG", targetvalue: "234" }, { id: 4, name: "ben", code: "SP", targetvalue: "234" },];
const arrobj3 = [{ id: 1, name: "sonu", code: "IT", targetvalue: "908" }, { id: 3, name: "lisa", code: "FI", targetvalue: "234" }, { id: 4, name: "ben", code: "FI", targetvalue: "234" },];

console.log(checkIdList(arrobj1, arraylist));
console.log(checkIdList(arrobj2, arraylist));
console.log(checkIdList(arrobj3, arraylist));

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

Determine whether a given date falls on today or tomorrow in Swift

I am working with an array of integers that represent today's and tomorrow's dates. My goal is to separate this array based on the type of day let dateCollection = [ 1633722900, 1633730500, 1633754910, 1633758913, 1633820400, ...

Creating a file structure for JavaScript files in a Vue CLI project

When structuring my Vue CLI project, I'm struggling to find clear documentation on best practices. Currently, I have 10 modules each with an associated JS file. My approach so far involves organizing all the pages in my router.js within a views direc ...

JavaScript countdown isn't functioning when the button is clicked

I'm facing an issue with implementing a JavaScript redirect countdown feature... Below is the HTML code for a button, which should trigger the countdown upon clicking: <footer> <button type="submit" class="btn btn-primary"> &l ...

PHP - update the value of the first element in an array

What is the best way to write data to the first element of an array? I am aware that using reset can retrieve the first element... but unfortunately, it does not allow for writing to it directly. ...

What is the best way to change any timezone to the local timezone using JavaScript?

Check out the code snippet below that is designed to convert a date to the local timezone: function convertDateToServerDate(incomingDate) { var serverOffset = new Date(); serverOffset = serverOffset.getTimezoneOffset(); var outgoingServerDate = new Date ...

Exploring Angular testing by using mock services to simulate the behavior of other services

I am familiar with how to mock a function call to a service. However, I am facing a scenario where my MainService acts as a wrapper for multiple other services. export class MainService { constructor( public service1: Service1, public service2 ...

javascript issue with Q promise not passing complete parameters

I am struggling to pass all three arguments successfully in my promise callback. The issue I'm facing is that only one argument is being received instead of the expected three: var asyncFunction= function(resolve) { setTimeout(function() { ...

Pass on the touchmove event from the panel to the content using jQueryMobile

Within my interface, I have a link labeled myLink located in a side panel labeled myPanel, along with some content labeled myContent. My goal is to: Tap and hold on the link myLink within the panel myPanel Have the panel myPanel close immediately Add an ...

Problem with Bootstrap-slider not loading correctly

I seem to be facing an issue with selecting DOM elements that are part of bootstrap-slider. When I try to target them with events like click, nothing happens. All events work fine when the page is refreshed. What could be causing this problem? $(document ...

The customized sweet alert button is failing to trigger its designated function

I integrated vue-swal to show a pop-up dialog with customized functionality. However, I faced an issue while modifying the swal. In my modified version, there are 3 buttons each with specific actions that should be triggered upon clicking. But for some rea ...

When accessing req.user in code not within a router's get or post method

Is there a way for me to access the data in the User schema outside of a post or get request? I am asking this because I would like to use this information elsewhere. The user schema is defined as follows: const mongoose = require('mongoose'); c ...

The request to retrieve data from the model at http://localhost:9000/model/data.json resulted in a 404

This is the path to my directory I have a npm server running on http://localhost:9000/ to utilize the cytoscape module. However, my server is unable to locate my json file. What could be the issue with my code? This is the source code of my index.js file ...

Obtaining a result from a jQuery Ajax call

I am exploring the use of JavaScript in an object-oriented style, and have a method that requires making a remote call to retrieve data for a webpage to function properly. To achieve this, I have created a JavaScript class to handle data retrieval in order ...

Error: The 2D list of objects is experiencing an IndexError due to the list index being out of range

Code snippet: class Grid: def __init__(self): self.matrix = [[Cell(i, j)] for j in range(5) for i in range(6)] # Additional methods def enter_letter(self, letter): if self.current_col == 5: return ...

Unspecified outcome of Ajax array as a choice in Select

I'm fairly new to working with AJAX / JSON and I'm having trouble figuring out how to parse an AJAX array response into a <select> dropdown. Despite going through several online tutorials and attempting different approaches to return the r ...

Issue encountered with ngrok causing an unidentified error in node.js while executing a server script

Recently, I've been encountering an error while trying to execute a server script in node.js. The error message I keep receiving is quite perplexing. https://i.sstatic.net/DMMSj.png Upon further investigation, I discovered that the problematic piece ...

Using Javascript to swap background images, ensuring that the initial image is shown only once

I have a query regarding the background image rotation on my HTML page. I am currently using the code below to change the background image, but I want the first image to be displayed only once while the rest continue rotating. Can anyone provide guidance o ...

What is the best approach for creating a select statement with parameters and iterating through it using PL/SQL?

Seeking guidance on how to create a for loop with parameters in a function using PL/SQL. Here is an example of what I am trying to achieve: CREATE OR REPLACE FUNCTION f_example(p_table, p_column) BEGIN FOR v_iter in (EXECUTE IMMEDIATE 'select ' ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Clickable CSS3 animations

Currently exploring the fundamentals of CSS3 animation and onclick events, but I've hit a roadblock. My objective is to utilize button id="3" to initiate the animation on the red square displayed here: https://jsfiddle.net/4swmegpn/ Additionally, I a ...