Introduction to the

Array, object, unique, only once, difference set

Retrieves the unique data set in the two object arrays, the difference set.

/ / the source code from https://30secondsofcode.org
const filterNonUniqueBy = (arr, fn) = >
  arr.filter((v, i) = > arr.every((x, j) = > (i === j) === fn(v, x, i, j)));
Copy the code

The code analysis

Array.prototype.filter is used to traverse the Array and get the filter. Array.prototype.every and fn are used to determine whether the item has been repeated.

Usage scenarios

Users participating in different marathons are obtained from the backend or database and collected. FilterNonUniqueBy is used to find users who have only participated in one marathon.

// Query the data of participating in xiamen Marathon 2019
const join2019 = [
    { id: 1.name: 'xiaoer'.join: ['Xiamen Marathon 2019'.'2018 Xiamen Marathon '] {},id: 2.name: 'xiaosi'.join: ['Xiamen Marathon 2019']]},// Query the data of participating in 2018 marathon
const join2018 = [
    { id: 1.name: 'xiaoer'.join: ['Xiamen Marathon 2019'.'2018 Xiamen Marathon '] {},id: 3.name: 'menty'.join: ['2018 Xiamen Marathon ']]},// Merge data
const users = [...join2019, ...join2018]

// Get the user who participated only once
/ / output:
/ / /
// {id: 2, name: "xiaosi", sales: 50000},
// {id: 3, name: "menty", sales: 150000}
// ]
const joinOnce = filterNonUniqueBy(users, (a, b) = > a.id === b.id)
Copy the code

Similar code

Retrieves a unique data set from an array.

/ / the source code from https://30secondsofcode.org
const filterNonUnique = arr= > arr.filter(i= > arr.indexOf(i) === arr.lastIndexOf(i))
Copy the code

Grow up together

In the confused city, there is always a partner to grow up together.

  • You can click on this if you want more people to see the articlegive a like.
  • If you want to inspire your mistress thereGithubGive aLittle stars.
  • If you want to communicate more with small two add wechatm353839115.

PushMeTop originally contributed to this article