Ramda处理JavaScript中的数组

时间:2018-10-25 16:47:40

标签: javascript arrays ramda.js

  var censusMembers = Object.freeze([
    {
    id: 1,
    name: 'Bob'
    }, {
    id: 2,
    name: 'Sue'
    }, {
    id: 3,
    name: 'Mary',
    household_id: 2
    }, {
    id: 4,
    name: 'Elizabeth',
    household_id: 6
    }, {
    id: 5,
    name: 'Tom'
    }, {
    id: 6,
    name: 'Jill'
    }, {
    id: 7,
    name: 'John',
    household_id: 6
    }
    ]);

这是我的数组 我想使用ramda函数计算具有家庭ID的元素的数量? 我该怎么办?

4 个答案:

答案 0 :(得分:2)

您还可以使用R.countBy使用R.has()来计数所有具有/不具有household_id的项目,然后使用{{3 }}:

true
const { pipe, countBy, has, prop } = R;

const censusMembers = Object.freeze([{"id":1,"name":"Bob"},{"id":2,"name":"Sue"},{"id":3,"name":"Mary","household_id":2},{"id":4,"name":"Elizabeth","household_id":6},{"id":5,"name":"Tom"},{"id":6,"name":"Jill"},{"id":7,"name":"John","household_id":6}]);

const countHouseholders = pipe(
  countBy(has('household_id')),
  prop('true'),
);

const result = countHouseholders(censusMembers);

console.log(result);

答案 1 :(得分:0)

不要使用函数filter来计数内容,因为创建数组只是为了获取长度。

您可以使用函数R.reduce,并在处理程序中检查键household_id

var censusMembers = Object.freeze([{id: 1,name: 'Bob'}, {id: 2,name: 'Sue'}, {id: 3,name: 'Mary',household_id: 2}, {id: 4,name: 'Elizabeth',household_id: 6}, {id: 5,name: 'Tom'}, {id: 6,name: 'Jill'}, {id: 7,name: 'John',household_id: 6}]);

// With household_id
//                                      (true is coerced to 1) = 1
console.log("With:", R.reduce((a, c) => ('household_id' in c) + a, 0, censusMembers));

// Without household_id
//                                         !(false is coerced to 0) = 1
console.log("Without:", R.reduce((a, c) => !('household_id' in c) + a, 0, censusMembers));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

答案 2 :(得分:0)

has似乎是您所缺少的:

var censusMembers = Object.freeze([
  {id: 1, name: 'Bob'}, 
  {id: 2, name: 'Sue' }, 
  {id: 3, name: 'Mary', household_id: 2 }, 
  {id: 4, name: 'Elizabeth', household_id: 6},
  {id: 5, name: 'Tom'}, 
  {id: 6, name: 'Jill'}, 
  {id: 7, name: 'John', household_id: 6}
]);

const countHouseholders = R.pipe(R.filter(R.has('household_id')), R.length)

console.log(countHouseholders(censusMembers))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

答案 3 :(得分:-1)

我不知道ramda,所以我不会猜到,但是在香草味(功能丰富)中:

censusMembers.filter((m) => { return m.hasOwnProperty('household_id') })