TransWikia.com

javascript check if array contains more than one element with exact same property

Stack Overflow Asked by Michael Kostiuchenko on November 20, 2021

I have an array of objects:

[
  {
   id: 1,
   sku: 'aaaa'
  },
  {
   id: 2,
   sku: 'bbbb'
  },
  {
   id: 3,
   sku: 'cccc'
  },
  {
   id: 4,
   sku: 'aaaa'
  }
]

How can I check that there are more than one element with the same sku property existing in the array?

For example: I have to elements with the same prop sku (‘aaaa’) – and in this case I need to do something in other case – nothing

4 Answers

const a = [
  {
   id: 1,
   sku: "aaaa"
  },
  {
   id: 2,
   sku: "bbbb"
  },
  {
   id: 3,
   sku: "cccc"
  },
  {
   id: 4,
   sku: "aaaa"
  }
];

a.reduce((acc, obj)=>{

    // looping through each sku & adding them in acc
    acc.push(obj.sku);
    
    // check if current sku already exits in acc.
    const duplicate = acc.filter(x=>x === obj.sku);
    
    if(duplicate.length>1){
          // do something or nothing with current obj as similar SKUs are found
          // i'm adding a new property called x=10 if same SKUs are found.
          obj.x = 10;
    }else{
          // do something or nothing with current obj as similar SKUs are found
          // i'm adding a new property called y=10 if not same SKUs.
          obj.y=10;
 }
 
 return acc;

}, []);

console.log(a);

Answered by micronyks on November 20, 2021

You can check like below array function 'some' will help you

 var arr = [
  {
   id: 1,
   sku: 'aaaa'
  },
  {
   id: 2,
   sku: 'bbbb'
  },
  {
   id: 3,
   sku: 'cccc'
  },
  {
   id: 4,
   sku: 'aaaa'
  }
]

const val = 'aaaa'

const isAvailable = arr.some(function(arrVal) {
        return val === arrVal.sku;
});

//here isAvailable will return true or false

Answered by Anku on November 20, 2021

You can use example code like this:

var a = [
  {
   id: 1,
   sku: 'aaaa'
  },
  {
   id: 2,
   sku: 'bbbb'
  },
  {
   id: 3,
   sku: 'cccc'
  },
  {
   id: 4,
   sku: 'aaaa'
  }
];

var b = {};
a.forEach(el => {
  if (b[el.sku]) {
    b[el.sku].count++;
  } else {
    b[el.sku] = { id: el.id, count: 1 };
  }
});

console.log(b);

Answered by Mahdy Aslamy on November 20, 2021

Use set to get an array holding unique skus and compare the length

var skus = items.map(v=>v.sku);
var uniqueSkus = new Set(skus);
console.log(skus.length === uniqueSkus.size)

Answered by lastr2d2 on November 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP