-1

I need to find true of false if my array contain duplicate object value.

Suppose I have this array of objects

const array = [
    {
        id: "id1",
        quantity: 3,
        variation: "red",
        tax: 40
    },
    {
        id: "id1",
        quantity: 3,
        variation: "red",
        tax: 40
    },
    {
        id: "id2",
        quantity: 3,
        variation: "red",
        tax: 40
    }
]

Here I have to get true because here id1 come twice in this array. If This array contain unique id everywhere then it should return false. How can I do that. I am not getting proper solution.

3
  • 1
    Does it have to be only id or any property? Every other property is identical. Commented Oct 23, 2022 at 12:15
  • Can you please share what you've tried that isn't working? Commented Oct 23, 2022 at 12:18
  • "I am not getting proper solution." is not really a clear question though. What are you stuck on? Do you know how to check values in an array? If not, you could start with a for loop. Commented Oct 23, 2022 at 12:18

1 Answer 1

0

You can use the following function:

function checkDuplicates(arr) {
    let result = false;
    let ids = [];

    for(let x = 0; x < arr.length; x++) {
        if(ids.includes(arr[x].id)) {
            result = true;
            break;
        } else {
            ids.push(arr[x].id);
        }
    }

    return result;
}

console.log(checkDuplicates(array))

Hope it helps.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.