0

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 }
]
Shidersz
  • 16,846
  • 2
  • 23
  • 48
Sandhya3478
  • 47
  • 2
  • 10
  • 2
    Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – Gonzalo.- May 16 '19 at 02:18

2 Answers2

0

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 }]
Darryl Ceguerra
  • 181
  • 1
  • 7
0

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;}
Shidersz
  • 16,846
  • 2
  • 23
  • 48