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

How to Perform an Inner Join on Javascript Arrays?

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 00:45:40948browse

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), []);

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},
];

Join Operation:

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

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' }
]

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!

Statement:
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