skip to Main Content

How to get all objects with the same value and then add them to resulting array?

I mean I need to find all duplicates by value (which is unknown in advance) and then return array of all unique objects with a key variant which holds array of duplicate objects or null if nothing found.

const products = [
  {
    position: 1,
    category: "jeans",
  },
  {
    position: 2,
    category: "tees",
  },
  {
    position: 3,
    category: "dress",
  },
  {
    position: 4,
    category: "dress",
  },
  {
    position: 5,
    category: "dress",
  },
];

// output
const output = [
  {
    position: 1,
    category: "jeans",
    variants: null,
  },
  {
    position: 2,
    category: "tees",
    variants: null,
  },
  {
    position: 3,
    category: "dress",
    variants: [
      {
        position: 3,
        category: "dress",
      },
      {
        position: 4,
        category: "dress",
      },
      {
        position: 5,
        category: "dress",
      },
    ],
  },
];

2

Answers


  1. You could use something like the following:

    const products = [
      {
        position: 1,
        category: "jeans",
      },
      {
        position: 2,
        category: "tees",
      },
      {
        position: 3,
        category: "dress",
      },
      {
        position: 4,
        category: "dress",
      },
      {
        position: 5,
        category: "dress",
      },
    ];
    
    const output = [];
    
    // create an object to hold categories we've encountered so far
    const categoryMap = {};
    
    // iterate through all our producs
    for (const product of products) {
      // destructure category from product
      const { category, ...rest } = product;
    
      // if we don't find the category in our category map, add it to the map
      // note that variants are empty for now because we haven't encountered duplicates
      if (!categoryMap[category]) {
        categoryMap[category] = {
          ...rest,
          variants: [],
        };
    
        // also push the category to the output, since it's the first occurrence of the category
        output.push(categoryMap[category]);
      }
    
      // finally, push any variants of the category to the empty variants array
      // note how we used the O(1) lookup of the hashmap to simplify finding duplicate categories
      categoryMap[category].variants.push({ ...rest, category });
    }
    
    console.log(output);

    In essence, we’re creating a lookup map which stores all the categories, and then appending any variants to the category already in the map.

    As for why, it saves us the effort of having to constantly check for duplicates in the array by utilizing the O(1) lookup time of JS objects.

    Login or Signup to reply.
  2. here you go:

    
    
    // "algorithm" -> create a new object, and add the category as the key, and the value is an array of products
    // if the category already exists, then push the product to the array
    // then, get the keys of the object, and map over them
    // for each key, get the value, and create a new object with the category, position, and variants
    // if the variants are more than 1, then add the variants, else, add null
    // then, return the new object
    // that will give you the desired result
    const categorized = products.reduce((acc, product) => {
      // Extract the category property from the product object using destructuring assignment.
      const { category } = product
    
      // Check if the category already exists in the accumulator object.
      if (!acc[category]) {
        // If the category does not exist, create a new array with the product and add it to the accumulator object.
        acc[category] = [product]
      } else {
        // If the category already exists, add the product to the existing array.
        acc[category].push(product)
      }
    
      // Return the accumulator object.
      return acc
    }, {})
    // Convert the accumulator object to an array of objects with the category, position, and variants properties.
    const parsed = Object.keys(categorized).map((key) => {
      const item = categorized[key]
      const tempItem = {}
      tempItem['category'] = key
      tempItem['position'] = categorized[key][0].position
      tempItem['variants'] = item.length > 1 ? item : null
      return tempItem
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search