I am looking for some help in relation to the next code:

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;
});

So, after I sort the items of the array in ascending or descending order, I want to extract the sub-array of objects that share the same value. Is there an easy approach for this in javascript?

The output related to previous example should be like:

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

2 Answers

0
Shidersz On Best Solutions

Having the array of items sorted by value is good because you can take advantage of that and use Array.filter() to check if the previous item or the next one share the same value with the current inspected item on each iteration:

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;}

0
Darryl Ceguerra On

You can use javascript Filter

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

output:

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