>데이터 베이스 >MySQL 튜토리얼 >Javascript 배열에서 내부 조인을 수행하는 방법은 무엇입니까?

Javascript 배열에서 내부 조인을 수행하는 방법은 무엇입니까?

Linda Hamilton
Linda Hamilton원래의
2025-01-06 00:45:40963검색

How to Perform an Inner Join on Javascript Arrays?

데이터 조작을 위한 Javascript 배열의 내부 조인

문제 설명:

공통 키를 기반으로 두 개의 Javascript 배열을 단일 결과 배열로 결합, SQL의 JOIN 연산과 유사합니다.

주어진 배열:

  • 'userProfiles': 'id' 및 'name' 속성이 있는 개체를 포함합니다.
  • 'questions': 'id', 'text' 및 ' CreatedBy' 속성.

해결책:

내부 조인 구현:

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

예제 데이터 세트:

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

조인 작업:

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

콘솔 출력:

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

위 내용은 Javascript 배열에서 내부 조인을 수행하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.