-2
    zones = [
      {zone:'A' : price:'20'},
      {zone:'B' : price:'20'},
      {zone:'C' : price:'20'},
      {zone:'A' : price:'20'},
    ];

this is my array of objects how do I find the duplicate value if zone 'A' is Repeated twice I need to Find That?

Alex baby
  • 19
  • 5

4 Answers4

0
zones = [{
    zone: 'A',
    price: '20'
  },
  {
    zone: 'B',
    price: '20'
  },
  {
    zone: 'C',
    price: '20'
  }
];

var result = []

for (let i = 0; i < zones.length; i++) {
  for (let k = 1; k < zones.length; k++) {
    if (zones[i].zone === zones[k].zone && i != k && result.indexOf(zones[i].zone) == -1) {
      result.push(zones[i].zone)
      console.log(zones[i].zone)
    }
  }
}
0

found this answer here : post 1

 var zones = [
    {zone:'A' : price:'20'},
    {zone:'B' : price:'20'},
    {zone:'C' : price:'20'},
    {zone:'A' : price:'20'},
 ];

 unique = [...new Set(zones.map(propYoureChecking => 
    propYoureChecking.zone))];
    if (unique.length === 1) {
    console.log(unique);
 }

and for normal arrays : post 2

You can do it a few different ways: here's one (from the post):

 const arry = [1, 2, 1, 3, 4, 3, 5];

 const toFindDuplicates = arry => arry.filter((item, index) => arr.indexOf(item) !== index)
 const duplicateElementa = tofindDuplicates(arry);
 onsole.log(duplicateElements);

// Output: [1, 3]
Tim
  • 49
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 25 '21 at 09:41
0

Your requirement is a bit vague but assuming you want to find the index of the duplicate object(s).


zones = [
{zone:'A', price:'20'},
{zone:'B', price:'20'},
{zone:'C', price:'20'},
{zone:'A', price:'20'},
];

const zoneAIndices = [];

zones.forEach((zone, index) => {
 if( zone.zone === 'A') {
   zoneAIndices.push(index);
 }
});

Now zoneAIndices[1] has the index of the duplicate item.

Note:

the zones array you have defined is incorrect, instead of : between zone and price it should be a ,

theekshanawj
  • 234
  • 2
  • 8
0

you can reduce code and simply create a function to choose key and count occurence like below

const zones = [
{zone:'A' , price:'20'},
{zone:'B' , price:'20'},
{zone:'C' , price:'20'},
{zone:'A' , price:'20'},
];

const countRepeat = (x,field) =>  zones.filter(element => element[field]===x).length
    
    console.log(countRepeat('A','zone')) // 2
    
    console.log(countRepeat('20','price')) //4

you can check more at : https://learnjsx.com/category/2/posts/es6-filterFunction

Ali
  • 78
  • 1
  • 3