Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS: Remove array of items from an array

Tags:

knockout.js

I have a problem with knockoutJS i can't figure out

I have two observableArrays; One containing all available items and one containing all selected items.

How can i return a new array, that contains all the available items ( with all the selected items removed from it)?

like image 625
Kristian Nissen Avatar asked Nov 05 '13 15:11

Kristian Nissen


People also ask

How do you slice an observable array?

The slice function is the observableArray equivalent of the native JavaScript slice function (i.e., it returns the entries of your array from a given start index up to a given end index). Calling myObservableArray. slice(...) is equivalent to calling the same method on the underlying array (i.e., myObservableArray().

How do you make an empty array observable?

To clear an observableArray you can set the value equal to an empty array.

How do you remove an object from observable?

To trigger an element deletion, simply send an event on the subject: this. deleteSubject. next({op:'delete', id: '1'});


3 Answers

I'd use .filter or ko.utils.arrayFilter, and .indexOf or equivalent:

this.remainingOptions = ko.computed(function(){
    return this.availableOptions().filter(function(option) {
        return this.selectedOptions().indexOf( option ) === -1;
    }.bind(this));
},this);

Fiddle: http://jsfiddle.net/p3RMD/1/

Edit: Also see the Knockout Projections plugin if you want more efficient .map and .filter methods on observableArrays

like image 63
antishok Avatar answered Sep 28 '22 16:09

antishok


The standard removeAll method should handle this. From documentation:

myObservableArray.removeAll(['Chad', 132, undefined]) removes all values that equal 'Chad', 123, or undefined and returns them as an array

Do you need to extract the available items without altering the original, all available items array?

like image 33
pax162 Avatar answered Sep 28 '22 15:09

pax162


If you want to return a new array, without modifying the original array, your best bet is to use a computed observable.

var ViewModel = function(){
    this.available = ko.observableArray([1,2,3,4,5]);
    this.selected = ko.observableArray([1,3,5]);

    this.remaining = ko.computed(function(){
        var remaining = ko.observableArray();
        remaining(ko.toJS(this.availableOptions))
        remaining.removeAll(this.selectedOptions());
        return remaining();
    }, this);
}

Here's a link to a working example:

http://jsfiddle.net/nathanjones/p3RMD/

Edit: fixed sample code.

like image 40
Nathan Jones Avatar answered Sep 28 '22 15:09

Nathan Jones