Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to find symetric differencebetween several array using filter and reduce? #36

Closed
alamenai opened this issue Feb 14, 2023 · 1 comment
Assignees
Labels
bug Something isn't working help wanted Extra attention is needed
Projects

Comments

@alamenai
Copy link
Owner

Steps to reproduce:

Targeted file: difference. js

Description:

The goal of this function is to find the asymmetric difference between two or more arrays. However, I found a silent bug when I was adding more unit tests.

Current implementation

export const difference = (...arrays) => {
    if (arrays.length === 1) return arrays[0]
    const args = Array.from([...arrays])
    let initArray = args[0];
    let differentElements = new Set();
    args.forEach(array => args.indexOf(array) !== 0 && isArray(array) &&
        array.forEach(value => !initArray.includes(value) && differentElements.add(value)))
    return Array.from(differentElements)
}

New implementation

export const diff = (arr1, arr2) => {
	return [
		...arr1.filter((item) => !arr2.includes(item)),
		...arr2.filter((item) => !arr1.includes(item)),
	];
};

Expected failed tests:

	it('should return an array with the uncommon elements between arrays ', () => {

               expect(diff([1, 2], [1, 2, 5])).toStrictEqual([5]); // passed

		expect(diff([1, 2], [1, 2, 3], [1, 2, 3, 4])).toStrictEqual([4]); // failed

		expect(diff(['a', 'b'], ['b', 'a'], ['a', 'b', 'c'])).toStrictEqual(['c']); // failed

		expect(diff([null], [undefined, null], [undefined, null, 'Ala'])).toStrictEqual(['Ala']); //failed

		expect(diff(['diorite', 'andesite', 'grass', 'dirt', 'pink wool', 'dead shrub'],['diorite', 'andesite', 'grass', 'dirt', 'dead shrub'])
		).toStrictEqual(['pink wool']); // failed
	});

	it('should return an empty array ', () => {
		expect(diff([1, 2], [1, 2], [1, 2])).toStrictEqual([]); //failed
	});

	it('should return the original array ', () => {
		expect(diff([1, 2])).toStrictEqual([1, 2]); //failed
	});
@alamenai alamenai added bug Something isn't working help wanted Extra attention is needed labels Feb 14, 2023
@alamenai alamenai added this to To do in Arrow via automation Feb 14, 2023
@alamenai
Copy link
Owner Author

Solved : StackOverFlow Answer.

Arrow automation moved this from To do to Done Feb 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working help wanted Extra attention is needed
Projects
Arrow
  
Done
Development

No branches or pull requests

2 participants