Utilizing the indexOf method to filter an array in a Next.js application with TypeScript

I have two arrays in my Next.js app

Array 1:

[

  { 
    identifier: "60a17722225f2918c445fd19",
    name: "Ben Awad",
    _id: "60c94480b8d43c28d0a6eb73
  },
  
  {
    identifier: "60a455d11fa62a1510b408f8",
    name: "dev ed"
    _id: "60bf62cede309f1a30fe88ab"
  }

]

Array 2:

[

  {
    name: "Ben Awad",
    _id: "60a17722225f2918c445fd19
  },

  {
    name: "dev ed",
    _id: "60a455d11fa62a1510b408f8"
  },

  {
    name: "Katlyn",
    _id: "60a52500ce96f30c14fdaff9"
  },

  {
    name: "Mike",
    _id: "60c95deeb8d43c28d0a6eb74"
  },

  {
    name: "Kassandra",
    _id: "60c960ddb8d43c28d0a6eb7a"
  }

]

I need a new array that contains all users from Array 2 except those who share ids with Array 1.

This is the logic I've implemented (Note that these arrays will change dynamically)

Me = Array 1 AllUsers = Array 2

const LookFriends =
    Me &&
    AllUsers.filter(({ _id }) => {
      return Me.friends.indexOf(_id) === -1;
});

console.log(LookFriends);

The expected output should be Katlyn, Mike, and Kassandra, but the console.log displays...

[

  {
    name: "Ben Awad",
    _id: "60a17722225f2918c445fd19
  },

  {
    name: "dev ed",
    _id: "60a455d11fa62a1510b408f8"
  },

  {
    name: "Katlyn",
    _id: "60a52500ce96f30c14fdaff9"
  },

  {
    name: "Mike",
    _id: "60c95deeb8d43c28d0a6eb74"
  },

  {
    name: "Kassandra",
    _id: "60c960ddb8d43c28d0a6eb7a"
  }

]

I'm struggling to filter an array based on another array, any suggestions?

Answer №1

To solve this problem, you should utilize the 'findIndex' method and directly compare the _id field:

const UniqueFriends =
    CurrentUser &&
    AllUsers.filter(({ _id }) => {
      return CurrentUser.friends.findIndex(friend => friend._id === _id) === -1;
});

Avoid using "indexOf" as it will compare the entire object instead of just the _id value.

Answer №2

To extract the IDs from the initial array and refine the second array by removing elements that do not match any ID in our object or set.

// utilizing an object
const identifiers = {}

array1.forEach(item => {
  identifiers[item.id] = true
})

const refinedArray = array2.filter(item => !identifiers[item._id])

// alternatively, using a Set
const identifiers = new Set(array1.map(item => item.id))

const refinedArray = array2.filter(item => !identifiers.has(item._id))

Answer №3

Feel free to test out this code snippet.

    Me && AllUsers.filter(({ _id }) => {
      let isExist = false;
      Me.friends.map((friend) => {
        if (friend._id === _id)
          isExist = true;
      });
      return isExist;
    });

Please inform me of the results.

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

JavaScript failed to read the entire variable

<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Exchange rate</title> <link rel="stylesheet"type="text/css"href="exstyle.css"/> </head> <body> <script type="text/javascript"> ...

When adding new elements to an array, the IDs of all objects become identical

When running the code below: dietDay.meals.forEach((meal) => { meal.mealProducts.forEach((mealProduct) => { if ( mealProduct.product.id && this.fetchedProductIds.includes(mealProduct.p ...

JavaScript - Verify if all properties belonging to an object are set to true

I'm facing a challenge with an object that contains various fields which could potentially be set to true for a user, similar to a list of achievements. If I have an object like {one: true, two: false, three: true}, how can I prevent the function from ...

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

Tips for retrieving specific data for display in an AngularJS application utilizing Node.js and MongoDB

Currently, I am in the process of developing a MEAN stack blog application. My main objective is to retrieve a specific "blog" from a list of blogs (displayed using ng-repeat) stored in my Mongo database via a Mongoose schema and then render it in a separa ...

Tips for retrieving all matching documents in MongoDB through Mongoose by performing a search operation across multiple fields in Node.js

` const fetchCandidates = (req, res, next) => { console.log(req.params); Candidate.find({ $or:[ {"name": req.params.name}, {"email": req.params.email}, {"role": req.params.role}, ...

Preparing a component for evaluation

When I execute the app and load views using @useview('resources/panels/data-table-panel.html'), everything works fine. However, running a component test results in failure due to a 404 error caused by the html file not being found. After changin ...

Exploring ways to query a mapped array in React Native

Struggling to search a mapped list in react native? While using a Flatlist would be easier, this task is currently causing me major frustration. If anyone has any insights or solutions, please share them! Here's a snippet of the code: import React ...

Implementing JSON responses in Express JS

My apologies for any language errors as English is not my first language, I am using Google Translate :) I have a question.. Here is the MySQL Query I am working with: SELECT destinations.*, questions.*, answers.* FROM destinations INNER JOIN questions ...

Executing Two Distinct JQuery Api Requests

I'm facing a challenge with integrating the data from two different API calls and processing them together. After receiving JSON responses from both calls, I convert them into GeoJSON format. The next step is to combine these geojson objects in anothe ...

The field Mutation.createMovement in GraphQL cannot be null for non-nullable fields

I'm currently developing a React/Postgres/Graphql application and encountering the error message "Cannot return null for non-nullable field Mutation.createMovement" when trying to execute the mutation in the frontend. I am using Apollo Client for Grap ...

Converting a string into a date format using JavaScript

Looking for a way to convert a string format like '19910127' into the date format 01/27/1991 using Javascript. Any suggestions on how this can be accomplished? ...

Exploring how to incorporate Express middleware into Firebase Functions for handling HTTPS requests

Encountering a challenge while using Express middleware with Firebase Functions. In this sample, a function is linked to the app() instance as shown below: app.get('*', (req, res) => { res.send(`Hello ${req.user.name}`); }); exports.autho ...

Executing a command to modify the local storage (no need for an API request) using redux persist in a React Native environment

Currently, I am facing an issue where I am attempting to trigger an action in Redux sagas to assign an ID to a local store: import { call, takeEvery } from 'redux-saga/effects'; import { BENEFITS } from '../actions/types'; function* ...

When extracting text using .text(), remember to include spaces between td elements

Is there a method to include space between td's when using .text()? I have searched extensively on Google but could only find information on how to trim space. The code I am currently using is as follows: for (var i = 0, len = rows.length; i < l ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

An assortment of elements with conditional statements

Can anyone help me with a function that returns the price of an item from a list? What happens if the item is not in the list? If it isn't, I want to display "No item found with that name" Any suggestions on how to achieve this? let items = [ ...

Tips on obtaining the current date format (e.g. dd/mm/yyyy or mm/dd/yyyy) on the client side

I am currently working with the datepicker control, and I need to adjust the date format based on my browser's settings - either dd/mm/yyyy or mm/dd/yyyy. For example: if my browser date is 22/06/2019, then I should use "dd/MM/yyyy" format in the dat ...

AJAX call retrieves unpopulated response from ColdFusion component

I've been struggling to make a call to a CFC using jQuery ajax in ColdFusion 11 on Windows 2008 R2 and IIS7.5. Despite researching multiple articles and Overflow posts on the subject, I can't seem to get a basic "Hello World" message to display o ...

Is it possible to add to the existing class based on a certain condition?

I have a coding challenge that I need help with. I have a set of code where I want to replace the old value in a class named "content" based on certain conditions. If the value within the class matches one of the values in an Array, then I need to append s ...