过滤和对象的uniq数组

时间:2018-10-23 12:24:39

标签: javascript filter uniq

我有一个对象数组。每个对象都有两个字段“类型”和“位置”。我想知道是否有任何对象(在此数组中)具有相同的“类型”和“位置”(并得到它)。我怎么知道呢?我知道如何过滤数组,但是如何与其他对象进行比较?

var array = forms.filter(function (obj) { return obj.type === 100 });

2 个答案:

答案 0 :(得分:1)

您可以使用Map,对相同类型/位置的对象进行分组,并对分组结果进行长度大于一的分组。

ObservableList<BooleanProperty> list = propertiesList.stream()
    .map(pane -> pane.changeProperty())
    .collect(Collectors.toCollection(() -> FXCollections.observableArrayList()));

BooleanBinding change = Bindings.createBooleanBinding(() -> true, list);

Button button = (Button) dialogPane.lookupButton(okButtonType);
button.disableProperty().bind(change.not());

答案 1 :(得分:1)

这是另一种方法:

const data = [
  { type: 'a', position: 1 },
  { type: 'b', position: 1 },
  { type: 'a', position: 1 },
  { type: 'a', position: 2 },
  { type: 'b', position: 2 },
  { type: 'c', position: 1 },
  { type: 'c', position: 1 }
]

const duplicates = data =>
  data.reduce((prev, el, index) => {
    const key = JSON.stringify({ p: el.position, t: el.type })
    prev[key] = prev[key] || []
    prev[key].push(el)
    if (index === data.length - 1) {
      return Object.values(prev).filter(dups => dups.length > 1)
    }
    return prev
  }, {})

console.log(duplicates(data))

相关问题