0

I am collecting a list of users for each request and pushing the list of users into arrays like below:

$.each(data, function (i, item) {
    jQuery.each(array, function (index, data) {
        if (data.UserId == user.Id) {
            //do nothing
        }
    });

    else{
        array.push(UserId:user.Id);
    }

});

Then, I am sending these data to the server:

jQuery.ajax({
    cache: false,
    type: "GET",
    url: "Handler.ashx",
    contentType: "application/json; charset=utf-8",
    data: { UsersData: JSON.stringify(array) },
    dataType: "json"
});

Now at next time, I have to find the object as previous and to delete the users who are not presented in users list and I have to send into request. Please can any one tell me how to add the list of users into array and to delete the users from array who are not in list of users.

2 Answers 2

1

If you have an array of data that you want to remove some off you can use the jQuery filter method (source) or even better the Array's filter method (source).

Note: The Array filter method (along with map, reduce and a few others) are part of ECMAScript 5 and aren't supported in some of the older browsers (basically the older IEs). There are plenty of shim out there though and the mdn docs all show how to implement the methods yourself (but here's a good shim if you want them all).

Here's how you'd use it:

var array = [1,2,3,4,5,6];
var filteredArray = array.filter(function (item /*current item in the array*/) {
    return item % 2; //return a boolean
});
console.log(filteredArray); // [1,3,5]

You then have a subset you can pass into your AJAX method.

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

3 Comments

Just remember that array.filter isn't supported in IE7 and under, so if IE7 support is needed either use jQuery's method, or use something like underscore – OR just do it in a loop.
@DougNeiner true, I've updated the answer with that clarification
how to compare two arrays and how to delete the item?
0

JavaScript offers several ways to easily add to or remove from arrays.

// add "7" to the array
var nums = [1,2,3,4,5,6];
nums.push(7);

// remove "3" from the array (index position #2)
nums.splice(2,1);

// find "5" and remove it
nums.splice(nums.indexOf(5), 1);

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.