List 使用Ramda向数组中的最后一个引用对象添加字段的最佳方法是什么?

List 使用Ramda向数组中的最后一个引用对象添加字段的最佳方法是什么?,list,ramda.js,List,Ramda.js,假设我有一个简单的对象数组,所有对象都有一个类型字段: let arr = [ { "name": "First", "type": "test" }, { "name": "Second", "type": "test" }, { "name": "Third", "type": "test2" }, { "name": "Fourth", "type": "test2" }, {

假设我有一个简单的对象数组,所有对象都有一个类型字段:

    let arr = [
  {
    "name": "First",
    "type": "test"
  },
  {
    "name": "Second",
    "type": "test"
  },
  {
    "name": "Third",
    "type": "test2"
  },
  {
    "name": "Fourth",
    "type": "test2"
  },
  {
    "name": "Fifth",
    "type": "test3"
  },
  {
    "name": "Sixth",
    "type": "test3"
  }
    ]
使用Ramda将字段添加到每个类型的最后一个匹配项的最佳方法是什么

要获得:

    let newArr = [
  {
    "name": "First",
    "type": "test"
  },
  {
    "name": "Second",
    "type": "test",
    "last": true
  },
  {
    "name": "Third",
    "type": "test2"
  },
  {
    "name": "Fourth",
    "type": "test2",
    "last": true
  },
  {
    "name": "Fifth",
    "type": "test3"
  },
  {
    "name": "Sixth",
    "type": "test3",
    "last": true
  }
    ]

我真的不知道该怎么办!提前感谢!:)

这里有一个可能的解决方案:

//    f :: [{ type :: a }] -> [{ type :: a, last :: Boolean }]
const f = R.addIndex(R.map)((x, idx, xs) =>
  R.assoc('last',
          R.none(R.propEq('type', x.type), R.drop(idx + 1, xs)),
          x));

对于列表中的每个值,我们向前看,看是否有一个后续值具有相同的
类型
属性。

我猜测您的数据是按显示分组的,不同类型的元素不是分散的。如果这个猜测是错误的,那么就需要一个不同的解决方案

我的版本涉及两个助手函数,其中一个根据谓词对列表进行分组,谓词报告两个(连续)值是否属于一起:

const breakWhen = R.curry(
  (pred, list) => R.addIndex(R.reduce)((acc, el, idx, els) => {
    if (idx === 0 || !pred(els[idx - 1], el)) {
      acc.push([el])
    } else {
      acc[acc.length - 1].push(el);
    }
    return acc;
  }, [], list)
);
第二个a关注列表的最后一个元素:

const lastLens = R.lens(R.last, (a, s) => R.update(s.length - 1, a, s));
使用这两个函数,您可以构建如下函数:

const checkLasts = R.pipe(
  breakWhen(R.eqProps('type')),
  R.map(R.over(lastLens, R.assoc('last', true))),
  R.flatten
);

checkLasts(arr);
breakWhen
的实现非常糟糕。我相信还有更好的。该函数结合了Ramda和



这与David Chambers的解决方案略有不同,因为它没有向其余元素添加
last:false
属性。但很明显,它更复杂。如果数据没有按预期分组,其中任何一个都会失败。

我不确定这是否有帮助,但您的数据是否总是按这种方式分组,以便所有类型的“test”都排在任何“test2”等之前,或者它们是否会混在一起?谢谢您的回答!!这提供了伟大的洞察力!这两种解决方案都适用于我的案例,尽管对于这样一个简单的场景来说,这看起来确实相当复杂!非常感谢!