Eliminate duplicates from an array using ES6 and values as criteria

Here is an array that I need to manipulate:

const array = [
{id: 3, amount: 100, productId: 10, title: "Color/Red", variantChildren: Array(0)},
{id: 4, amount: 5, productId: 10, title: "Color/Green", variantChildren: Array(2)},
{amount: 0, variantChildren: {…}, title: "Color/Red"},
{amount: 0, variantChildren: {…}, title: "Color/Green"},
{amount: 0, variantChildren: {…}, title: "Color/Purple"}
]

I want to remove items with an amount of 0 using either .filter() or .forEach().

This would result in a new array without the zero amounts:

const newArray = [
{id: 3, amount: 100, productId: 10, title: "Color/Red", variantChildren: Array(0)},
{id: 4, amount: 5, productId: 10, title: "Color/Green", variantChildren: Array(2)},
{amount: 0, variantChildren: {…}, title: "Color/Purple"}
]

Answer №1

Transform the array into a Map by filtering out items that are duplicates or have a total less than or equal to 0.

Then, convert the Map's .values() iterator into an array using Array.from().

const data = [{"id":3,"amount":100,"productId":10,"title":"Color/Red","variantChildren":[]},{"id":4,"amount":5,"productId":10,"title":"Color/Green","variantChildren":[null,null]},{"amount":0,"variantChildren":{},"title":"Color/Red"},{"amount":0,"variantChildren":{},"title":"Color/Green"},{"amount":0,"variantChildren":{},"title":"Color/Purple"}];

const result = Array.from(
  data.reduce((acc, o) =>
    !acc.has(o.title) || o.amount > 0 ? acc.set(o.title, o) : acc, new Map())
  .values()
);

console.log(result);

Answer №2

const itemsArray = [
  {id: 3, amount:100, productId:10, title:"Color/Red", variantChildren:Array(0)},
  {id: 4, amount:5, productId:10, title:"Color/Green", variantChildren:Array(2)},
  {amount:0, variantChildren:{}, title:"Color/Red"},
  {amount:0, variantChildren:{}, title:"Color/Green"},
  {amount:0, variantChildren:{}, title:"Color/Purple"},
  {id: 5, amount: 3, productId: 11, title: "Color/Green", variantChildren: Array(2)},
  {id: 6, amount: 10, productId: 12, title: "Color/Red", variantChildren: Array(0)},
  {amount: 2, variantChildren: {}, title: "Color/Purple"},
  {amount: 0, variantChildren: {}, title: "Color/Purple"}
];

const findNonZeroItems = arr => {
  const titleItemsMap = arr.reduce((acc,item) => {
    const { title, amount } = item;
    if(acc[title]) acc[title].push(item);
    else acc[title] = [item];
    return acc;
  }, {});
  
  const result = Object.values(titleItemsMap).reduce((acc, titleItems) => {
    const filteredItems = titleItems.length > 1
      ? titleItems.filter(item => item.amount !== 0)
      : titleItems;
      
    return [...acc, ...filteredItems]
  }, []);
  
  return result;
}

console.log( findNonZeroItems(itemsArray) );

Answer №3

let unfilteredArray = [{amount: 0}, {amount: 0}, {amount: 1}, {amount: 2}]
let tempArray = [];
let filteredArray = unfilteredArray.filter((value, index, arr) => {
  let isUnique = !(tempArray.map(v => v.amount).includes(value.amount))
  tempArray.push(value)
  return isUnique;
});
console.log(filteredArray);

Learn more about Array Filter on MDN

The provided code may seem complex at first glance. In essence, the filter method iterates through an array and applies a function that should return true or false. If true, the current value is added to a new array, otherwise it is omitted. In this case, the function inspects the temporary array for uniqueness based on the 'amount' property of each element. The temporary array is updated with each iteration to ensure that no duplicate 'amount' values are present in the final filtered array.

Answer №4

When utilizing methods like .filter or .forEach, it is necessary to iterate through each element and remove any duplicates found at lower indexes.

const array = [
    {id: 3, amount: 100, productId: 10, title: "Color/Red"},
    {id: 4, amount: 5, productId: 10, title: "Color/Green"},
    {amount: 0, title: "Color/Red"},
    {amount: 0, title: "Color/Green"},
    {amount: 0, title: "Color/Purple"}
]

const result = array.filter((el, i) => {
    const dupIndex = array.findIndex(e => e.amount === el.amount)
    return i <= dupIndex
})

console.log(result)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do not execute the JavaScript code if the cookie is present

I am dealing with a code that displays an irritating exit intent overlay when the back button is pressed, but I need it to not appear if a specific cookie is present. This particular cookie is created by my exit button. JavaScript: function dontshow(){ ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

Is it possible to create dynamic tabs using Bootstrap on .aspx pages?

I am facing an issue with my code. I have written a JavaScript function that enables moving to the next tab when clicking on tabs, but I also want to move to the next tab when clicking on a specific button. The script works as expected, except for one prob ...

Problems with the zoom functionality for images on canvas within Angular

Encountering a challenge with zooming in and out of an image displayed on canvas. The goal is to enable users to draw rectangles on the image, which is currently functioning well. However, implementing zoom functionality has presented the following issue: ...

Issue with Dropup Menu not displaying on Safari 6

Experience a unique display when visiting the following URL in popular browsers such as FF, Chrome, and Opera- watch as the menu gracefully slides out while a red dropup menu appears at the bottom: A peculiar situation unfolds when viewing this page on Sa ...

Updating a specific property within an array of objects by identifying its unique id and storing it in a separate array of objects

Struggling to merge these two arrays? Look no further! By comparing the parent id to child parentsId, you can effortlessly push the second array as an extra property to its parent. Save yourself hours of frustration and achieve your desired output with a l ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

The issue arises when attempting to execute an Ajax function within a JQuery append method, causing malfunction

My JQuery append function is calling an ajax function within the onChange method. Here is my code snippet: var data='<?php echo $data; ?>'; var tambah=1; var txt=1; function add_fullboard_dalam_kota(){ function showU(str) { ...

Utilizing Three.js with interactive functionalities and advanced transformation controls

I'm facing an issue with my project where I am using three.interaction to capture click events on certain objects and add transformControls to them. The problem I'm encountering is that the transform controls seem to block the click event on oth ...

How to leverage the parent component scope within the b-table slot

I am working with a v-slot in a <b-table> to create a link. The link's initial part consists of data from the source. However, there is a parameter in the querystring that I need to include in the link. How can I access the scope of my data con ...

Is it possible for Angular and Flux to collaborate harmoniously?

Flux is a unique unidirectional data flow concept developed by the React team, offering various benefits such as Undo/Redo functionality, ease of testing, maintaining a single app state, and more. Exploring the idea of integrating Flux with AngularJs could ...

Combining JSON array objects in Vanilla Javascript to create a nested array based on a shared value

I have been searching for a solution to address my specific issue but have not found an exact match. If there is a similar question, please provide a link to the solution. I am looking to merge an array of objects that share a common value using vanilla J ...

Angular: Transferring dynamic functions between parent and grandchild components

For my angular application, I am developing a versatile table component that can accept inputs for rows, columns, as well as handle various action button functions to render the table. The end result should resemble something like this: https://i.sstatic.n ...

Leveraging the wheelDelta property in the onmousewheel event handler with Script#

When working with Script#, I often utilize mouse events using the ElementEvent argument. However, one thing seems to be missing - the WheelDelta property for handling the onmousewheel event. Can anyone provide guidance on how to access this property in t ...

What could be causing the malfunction of this Ajax conditional dialog?

Can anyone help me troubleshoot this code? I've been trying to fix it for a while now, making multiple changes, but still can't find the solution. If you have any ideas please let me know, I haven't seen any errors in the console. The fir ...

Exploring the world of third-party widgets: Comparing Angular, jQuery, and traditional JavaScript

I have a plan to develop a simple embeddable widget similar to Google ads or Facebook like box. Users will be able to easily add the widget to their website and I will extract some parameters to fetch data from my servers. Previously, I relied on jQuery f ...

Encountering a Next.js prerendering issue when using getStaticPaths

I am currently developing a Next.js application. Here is the structure of my files: cpanearme -components -listitem.js -pages -home -index.js -firm -[id].js Below is the code for a list item that redirects to the dynamic rout ...

Uncertainty arises when trying to understand the callback function supplied to the `addEventListener` method in JavaScript

Question: I was recently exploring JavaScript's native addEventListener function. Typically, we use it like this: js selectElement.addEventListener('change', (event) => { const value = event.target.value }); However, when studying the ty ...

What is the most effective approach to take when the back button on a browser is pressed?

I have encountered an issue with my application related to the back browser buttons, as clicking on them messes up the functionality within the app. Therefore, I am considering two potential solutions: Solution 1: I came across a website that offers a ja ...

Is there a way for me to extract an image from Open Flash Chart 2?

After attempting to follow this tutorial, I discovered that it was not functioning properly. Although my server side is operating correctly, I encountered an issue in Firefox when trying to access the instance of ofc and call post_image. The error messag ...