0

I was trying one simple piece of code in which an array of objects are present and each object is having another array of products(with duplicate values). I wanted to combine all the products array together without any duplicates. Already reached half of iteration process but not able to remove duplicates, is there any way to iterate the values (as it is itself having key value as object 1 and its data..)

please suggest any other optimized way if possible. I'm new to JavaScript so pardon any silly mistakes made Thanks in advance.

enter image description here

3 Answers 3

1

You can do it using concat, Set and Array.from:

const object1 = { products: ['1', '2', '3'] }
const object2 = { products: ['1', '2', '3', '4'] }
const object3 = { products: ['5'] }

// Merge all the products in one Array
const products = object1.products
  .concat(object2.products)
  .concat(object3.products);

// Create a Set, with the unique products
const set = new Set(products);

// Convert the Set to an Array
const uniqueProducts = Array.from(set);

console.log(uniqueProducts)

Sign up to request clarification or add additional context in comments.

5 Comments

arr.forEach((value,index,arr)=>{ array.push(value.object1.products,value.object2.products,value.object3.products) }) console.log("arr after concat "+array) var set= new Set(array); console.log(set) const unique=Array.from(set); console.log("newest array: "+ unique) tried adding this piece of code output is yet the same.
OUTPUT: arr after concat str1,str2,str3,str2,str5,str5,str4,str5,str6,str7,str7,str8,str9 Set { [ 'str1', 'str2', 'str3', 'str2', 'str5', 'str5' ], [ 'str4', 'str5', 'str6', 'str7' ], [ 'str7', 'str8', 'str9' ] } newest array: str1,str2,str3,str2,str5,str5,str4,str5,str6,str7,str7,str8,str9
You don't need to use forEach and you should send a flat Array to the Set. Just try to understand and follow my example above strictly and apply it to your use-case. If you Run the code snippet above, you will see it works correctly.
Its working fine with your way.Thanks .But if we have say 10 objects ,how can we iterate it into its deep level to get the product array.
If you have many objects (instead of only 3), then it's reasonable to iterate over them and create a new resulting flat array, and later pass the array to the Set. You can iterate with any JS function you want, but I would prefer using reduce or forEach. If the answer helped you - you can consider accepting it. Thank you! :)
0

To remove duplicates you can use Set, it keeps all items unique, then you can cast it to Array.

Array.from(new Set(array))

Comments

0

there are many ways to achieve this:

  1. you can use filter to remove duplicate elements:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter by reading in value, its index and array in filter function

a quick search link: https://codeburst.io/javascript-array-distinct-5edc93501dc4

  1. you can always write a method for merge which would be good in terms of error handling, corner case checks, so that above action dont result into error, example:

function MergeUniqueProductFromDictToArry(fromDict, productKey, toArray) {
  //check if for the array in which we need to merge
  if(!toArray) {
    toArray = [];
  }
  //check for validity
  if(!fromDict || !productKey || !fromDict[productKey] || fromDict[productKey].length == 0) {
    return toArray;
  }  
  for(var ix in fromDict[productKey]) {
    //check if product already exist
    if(toArray.indexOf(fromDict[productKey][ix]) === -1) {
      toArray.push(fromDict[productKey][ix]);
    }
  }
  return toArray;
}
var object1 = {products: ["p1", "p2", "p1"]};
var object2 = {products: ["p3", "p2"]};
var object3 = {products: ["p4", "p2"]};
var uniqueProducts = MergeUniqueProductFromDictToArry(object1, "products", null);
uniqueProducts = MergeUniqueProductFromDictToArry(object2, "products", uniqueProducts);
uniqueProducts = MergeUniqueProductFromDictToArry(object3, "products", uniqueProducts);
console.log(uniqueProducts);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.