跳至主要内容

difference

🔸 題目描述

請實作一個名為 difference 的函式,該函式接收兩個陣列作為參數。函式的功能是回傳只在第一個陣列中存在、在第二個陣列中不存在的元素,並且避免對重複值進行多餘的操作。

difference([], []); // []
difference([1, 1, 2, 3], [2, 3]); // [1, 1]
difference([1, 2, 3], [1, 2, 3, 4]); // []
difference([4, 3, 2, 1], [1, 2, 3]); // [4]

Tests

import { describe, expect, test } from "@jest/globals";
import difference from "./difference";

describe("difference", () => {
test("returns elements only present in the first array", () => {
expect(difference([], [])).toEqual([]);
expect(difference([1, 1, 2, 3], [2, 3])).toEqual([1, 1]);
expect(difference([1, 2, 3], [1, 2, 3, 4])).toEqual([]);
expect(difference([4, 3, 2, 1], [1, 2, 3])).toEqual([4]);
});
});

Solutions

function difference(array: any[], values: any[]): any[] {
const result = [];
for (const element of array) {
if (!values.includes(element)) {
result.push(element);
}
}
return result;
}