提取共享相同值的子数组

时间:2019-05-16 02:15:21

标签: javascript arrays

我正在寻找有关下一个代码的帮助:

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 37 },
  { name: 'Zeros', value: 37 }
];

// Sort by value
items.sort(function (a, b) {
    return a.value - b.value;
});

因此,在按升序或降序对数组的items进行排序之后,我想提取共享相同值的对象的子数组。在javascript中有一种简便的方法吗?

与先前示例相关的输出应类似于:

[
  { name: 'Magnetic', value: 37 },
  { name: 'Sharpe', value: 37 },
  { name: 'Zeros', value: 37 }
]

2 个答案:

答案 0 :(得分:0)

您可以使用javascript https://regex101.com/r/lS5tT3/231

items.filter((i)=>{
    let duplicate = items.filter((x)=> {
        return x.value === i.value;
    })
    // Return if has duplicate
    return duplicate.length > 1
})

输出:

[{ name: 'Magnetic', value: 37 },  { name: 'Sharpe', value: 37 }, { name: 'Zeros', value: 37 }]

答案 1 :(得分:0)

具有按value排序的项目数组是一件好事,因为您可以利用它并使用Array.filter()来检查上一个或下一个项目是否与当前检查的项目共享相同的值在每次迭代中:

var items = [
  {name: 'Edward', value: 21},
  {name: 'Sharpe', value: 37},
  {name: 'And', value: 45},
  {name: 'The', value: -12},
  {name: 'Magnetic', value: 37},
  {name: 'Zeros', value: 37},
  {name: 'foo', value: 21}
];

// Sort by value.

items.sort((a, b) => a.value - b.value);

console.log("Sorted items:", items);

// Filter elements that share same value.

let onlyDups = items.filter((o, i, arr) =>
{
    return (i - 1 >= 0 && (arr[i - 1].value === o.value)) ||
           (i + 1 < arr.length && arr[i + 1].value === o.value);
});

console.log("Items that share value:", onlyDups);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}