2

I'm looking for more elegant and efficient way to toggle object in array.

So my arr is:

let arr = [
   {id: 2},
   {id: 3},
   ...
] 

Now I'm doing it like this:

if (arr.find(function(element) { return element.id === upload.id } )) {
    arr = arr.filter(function(element) {
        return element.id !== upload.id;
    });
}
else {
    arr.push(upload)
}
0

3 Answers 3

2
const index = arr.findIndex(function(element) { return element.id === upload.id });
if (index > -1) {
    arr.splice(index, 1);
}) else {
    arr.push(upload);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, my idea is find index of seeking element and if exists remove item from array using splice.
Edit the question and add some meaningful comments on them, guide user to understand the solution you provided.
1

If you toggle the object often, you could use a hash table for the indices of the array.

var hash = Object.create(null);

function update(array, item) {
    if (hash[item.id] !== undefined) {
        array.slice(hash[item.id], 1);
        hash[item.id] = undefined;
    } else {
        hash[item.id] = array.push(item) - 1;
    }
}

Comments

0
const toggle = (arr, obj) => arr.includes(obj) ? arr.splice(arr.indexOf(obj), 1) : arr.push(obj);

1 Comment

Your option won't work, becuase it doesn't check id.

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.