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

【Q678】实现一个函数 keyBy #697

Open
shfshanyue opened this issue Jul 30, 2021 · 2 comments
Open

【Q678】实现一个函数 keyBy #697

shfshanyue opened this issue Jul 30, 2021 · 2 comments
Labels

Comments

@shfshanyue
Copy link
Owner

shfshanyue commented Jul 30, 2021

类似 lodash.keyBy,这里仅仅考虑第二个参数为函数的情况

// Output: {
//   "1": {
//     "id": 1,
//     "name": "山月"
//   },
//   "2": {
//     "id": 2,
//     "name": "shanyue"
//   }
// }
keyBy([{ id: 1, name: '山月' }, { id: 2, name: 'shanyue' }], x => x.id)
@shfshanyue
Copy link
Owner Author

shfshanyue commented Jul 30, 2021

function keyBy (list, by) {
  return list.reduce((acc, x) => {
    acc[by(x)] = x 
    return acc 
  }, {})
}

@Yinzhuo19970516
Copy link

这里其实是利用对象的键都是有序的,把类数组转成了对象

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants