Divide an array of objects into two separate arrays based on whether the items match or not

const users = 
[
  {
    _id: "5fbfa729fc46a415ce5503a6",
    first_name: 'Allen',
    last_name: 'Border',
    timestamp: 1606395689121,
    key: [ "5fbf6f91aff7f3320a906547", "5fbfa748fc46a415ce5503a8" ]
  },
  {
    _id: "5fbfa6fbfc46a415ce5503a4",
    first_name: 'james',
    last_name: 'roger',
    timestamp: 1606395689125
  },
  {
    _id: "5fbf6f91aff7f3320a906547",
    first_name: 'david',
    last_name: 'gosh',
    timestamp: 1606395689130,
    key: [ "5fbfa729fc46a415ce5503a6" ]
  },
  {
    _id: "5e4e74eb380054797d9db623",
    first_name: 'Ricky',
    last_name: 'bichel',
    timestamp: 1606395689131
  }
]

const user_id = "5fbfa748fc46a415ce5503a8";

How can we categorize data as match or not match based on the provided user_id? The matched data should contain records where user_id matches with a value in users.key, while the not match data should contain records where there is no match. Is it possible to separate these two results?

This approach does not seem to be working properly.

const result = users.key.indexOf(user_id);

console.log(users.storyMute)

Answer №1

One effective way to utilize Array.prototype.reduce() is as follows:

const users=[{_id:"5fbfa729fc46a415ce5503a6",first_name:"Allen",last_name:"Border",timestamp:1606395689121,key:["5fbf6f91aff7f3320a906547","5fbfa748fc46a415ce5503a8"]},{_id:"5fbfa6fbfc46a415ce5503a4",first_name:"james",last_name:"roger",timestamp:1606395689125},{_id:"5fbf6f91aff7f3320a906547",first_name:"david",last_name:"gosh",timestamp:1606395689130,key:["5fbfa729fc46a415ce5503a6"]},{_id:"5e4e74eb380054797d9db623",first_name:"Ricky",last_name:"bichel",timestamp:1606395689131}]
const user_id="5fbfa748fc46a415ce5503a8"

const {matching, nonMatching} = users.reduce((acc, userRecord) => {
  userRecord?.key?.includes(user_id)
  // or, if you need to compare by _id
  // userRecord._id === user_id
    ? acc.matching.push(userRecord)
    : acc.nonMatching.push(userRecord)
  return acc
}, {matching: [], nonMatching: []})

console.log(matching)

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 clipboardjs copy feature doesn't seem to be functioning correctly at the

Following the Ajax response, the click event seems to be functioning properly. However, it appears that the clipboardjs copy functionality is not working. Is there a way to trigger the clipboardjs copy functionality? $.ajax({ cache: false, type ...

Once chosen, zoom in on the map to view the results

I am facing an issue with multiple selects in my code, where one select depends on the result of another. The ultimate goal is to zoom in on the area that has been searched and found, but unfortunately, it is not functioning as expected. If you'd lik ...

Populate DataGrid using an input through AJAX and jQuery technology

I've been grappling with a persistent issue that's been bothering me for days now. Here's the scenario: Currently, I have a DataGrid that is empty and an Input Text field in place that utilizes AJAX and jQuery to display a list of available ...

What is the best way to handle this JSON format in Android development?

Struggling to Decode the Following JSON Data Structure? { "district": [ { "1": { "name": "Lucknow", "block": [ { "1": "Block1", "2": "Block2", ...

Removing a custom JavaScript reference from a Drupal 7 subtheme is a task that can be accomplished

After following the instructions for handling javascript in Drupal 7, I placed a "myjs.js" file in the js folder located at sites/all/themes/mytheme/js and added a line to the mytheme.info file (scripts[] = js/myjs.js). Upon inspecting the page source of m ...

Trouble with video element and css not updating as expected based on conditions

I'm currently developing a video gallery featuring multiple videos that play sequentially. My goal is to eliminate the play button once it's clicked and display controls instead. I've attempted to use useRef and useState within useEffect, bu ...

Maintaining optimal frames per second using three.js

When using a WebGLRenderer instance with antialias = true, performance problems become evident as the resolution increases, particularly on retina displays (window.devicePixelRatio === 2). As it is not feasible to switch antialiasing modes dynamically, th ...

Just ran $npm install and encountered an error message: "Module '../lib/utils/unsupported.js' not found."

Returning to work on a React project after switching from the Rails environment, I encountered an issue where I am unable to run NPM commands in my Mac terminal. Despite trying various solutions I found online, none seem to be effective. The real concern i ...

Adding new columns to an ndarray that was created with numpy.genfromtxt

I recently used numpy.genfromtxt to create an ndarray from a txt file. The contents of the txt file are structured as follows: 2505000 10.316 1.936 0.025 0 15 0 0 10.316 1.937 0.028 0 15 0 0 10.316 1.943 0.028 ...

Conceal flex items when there is inadequate space available

I need help with customizing my JIRA timeline chart to show information about epics in progress. When an epic spans multiple releases, there is enough space on the timeline bar to display all relevant details. However, if an epic only spans one release, th ...

Continuously improving the form as they evolve

I am interested in creating a form that automatically sends data when users make changes to it. For instance: Imagine a scenario where a moderator is editing an article and changes values in a select field. As soon as the change is made, an ajax request ...

AngularJS is throwing an error message stating: "[$parse:syntax] There is a syntax error with the use of the @ symbol and

I've encountered an issue with my code snippet where I keep receiving errors. The content is dynamically generated but errors persist upon rendering. Despite attempting escape(), the issue remains unresolved. The value of $scope.teamInvites[index].t ...

Expressjs router.get('/') not firing as expected

I am facing an issue where I cannot access my express application's home page using the '/' route pattern. Instead, it only works with '/index'. My express version is 4.6. Even after trying app.use('/*', router), my appl ...

Arranging elements in a desired sequence within an array with PHP

I am working with two arrays. The first array $user contains image file names, and the second array $order specifies the desired order in which to sort the files. $user=array( "20163_100011100001_Guarantor_address_Proof.jpg", "20163_100011 ...

The most effective method for identifying neighboring players in a turn-based game

I'm currently working on a turn-based game where players can move and pick up weapons. While the visualization isn't perfect yet, player damage is still being controlled effectively. The graphics are created using the canvas API, and players can ...

Is there a way to make the onKeyDown event function properly in Next.js/React?

I'm currently developing a website with Next.js and am facing an issue trying to execute a simple function when a key is pressed. Strangely, the onKeyDown event isn't getting triggered as expected in my code snippet: <main onKeyDown={e => c ...

What is the best way to send a Node.js variable to the inner part of a Pug script tag?

I am attempting to pass a variable from my Node.js backend to a Pug template and then use that variable inside a JavaScript script tag within the Pug file. Here's a snippet of my Node.js code: app.get('/profile', function (req, res) { var ...

Guide on retrieving key-value pairs from a JSON reply

While attempting to extract the sid and date_created values from the JSON response received from Twilio after sending a text message, I encountered an issue where they were always returning as undefined. I experimented with using body.['sid'] an ...

Creating a digital item in a nested category using Mogoose

Within the realm of mongoose, there exists an object by the name of 'target' which houses an image (consisting of a name and extension). Each individual 'target' object also possesses a sub-collection of other objects, each containing t ...

What are the different ways in which :style is utilized in re-frame - with brackets, curly brackets, or simply without any characters?

For my current project, I am utilizing Clojure, ClojureScript, lein, shadow-cljs, Emacs, and CIDER to develop a dynamic web application. Typically, when building the project, I initiate the command cider-jack-in-cljs in Emacs, select shadow-cljs, opt for ...