Home > Database > Mysql Tutorial > How to Perform an Inner Join on Javascript Arrays?

How to Perform an Inner Join on Javascript Arrays?

Linda Hamilton
Release: 2025-01-06 00:45:40
Original
944 people have browsed it

How to Perform an Inner Join on Javascript Arrays?

Inner Join of Javascript Arrays for Data Manipulation

Problem Statement:

Combining two Javascript arrays into a single result array based on a common key, similar to the JOIN operation in SQL.

Given Arrays:

  • 'userProfiles': Contains objects with 'id' and 'name' properties.
  • 'questions': Contains objects with 'id', 'text', and 'createdBy' properties.

Solution:

Inner Join Implementation:

const innerJoin = (xs, ys, sel) =>
    xs.reduce((zs, x) =>
        ys.reduce((zs, y) =>        // cartesian product - all combinations
            zs.concat(sel(x, y) || []), // filter out the rows and columns you want
        zs), []);
Copy after login

Example Dataset:

const userProfiles = [
    {id: 1, name: "Ashok"},
    {id: 2, name: "Amit"},
    {id: 3, name: "Rajeev"},
];

const questions = [
    {id: 1, text: "text1", createdBy: 2},
    {id: 2, text: "text2", createdBy: 2},
    {id: 3, text: "text3", createdBy: 1},
    {id: 4, text: "text4", createdBy: 2},
    {id: 5, text: "text5", createdBy: 3},
    {id: 6, text: "text6", createdBy: 3},
];
Copy after login

Join Operation:

const result = innerJoin(userProfiles, questions,
    ({id: uid, name}, {id, text, createdBy}) =>
        createdBy === uid && {id, text, name});
Copy after login

Console Output:

Open your browser console to see the output.

[
  { id: 1, text: 'text3', name: 'Ashok' },
  { id: 2, text: 'text1', name: 'Amit' },
  { id: 2, text: 'text2', name: 'Amit' },
  { id: 4, text: 'text4', name: 'Amit' },
  { id: 5, text: 'text5', name: 'Rajeev' },
  { id: 6, text: 'text6', name: 'Rajeev' }
]
Copy after login

The above is the detailed content of How to Perform an Inner Join on Javascript Arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template