user2598808 user2598808 - 3 months ago 37
jQuery Question

KnockOut.JS compare two arrays and remove unique value from second array

I am working on Knockout.js.

var chosenFruit = ko.observableArray([]);
var allFruits = ko.observableArray([]);

allFruits = [ "Apple" , "Bananna" , "Grapes" , "Oranges"]
chosenFruit = ["Apple" , "Bananna" , "kiwi"]


Now, Since "Kiwi" is not present in First Array(That means, in allFruits), I want to remove "Kiwi" from second array (chosenFruit).

I want to compare both arrays and remove from second array - the value which is not present in first array.

That means , after comparison the second array should be :

chosenFruit = ["Apple" , "Bananna"]


Please suggest how to achieve this.

Thank You in Advance!

Answer

Use Array#filter method

var allFruits = ["Apple", "Bananna", "Grapes", "Oranges"],
  chosenFruit = ["Apple", "Bananna", "kiwi"];

console.log(
  // iterate and filter out element
  chosenFruit.filter(function(v) {
    // check value present in array
    return allFruits.indexOf(v) > -1;
  })
)


UPDATE 1 : If you want to keep the reference use Array#splice for removing the element.

var allFruits = ["Apple", "Bananna", "Grapes", "Oranges"],
  chosenFruit = ["Apple", "Bananna", "kiwi"];
// store length for iterating
var i = chosenFruit.length;

// iterate upto `0`
while (i--) {
  // check value exist in array
  if (allFruits.indexOf(chosenFruit[i]) == -1) {
    // if not present then remove it
    chosenFruit.splice(i, 1);
  }
}


console.log(chosenFruit);


UPDATE 2 : With knockout do something like this using Array#filter which generates a new filtered array.

var chosenFruit = ko.observableArray(["Apple", "Bananna", "Grapes", "Oranges"]);
var allFruits = ko.observableArray(["Apple", "Bananna", "kiwi"]);

console.log(
  chosenFruit().filter(function(v) {
    return allFruits().indexOf(v) > -1;
  })
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>


UPDATE 3 : If you want to update the observableArray then use remove() method with callback function.

var chosenFruit = ko.observableArray(["Apple", "Bananna", "Grapes", "Oranges"]);
var allFruits = ko.observableArray(["Apple", "Bananna", "kiwi"]);

allFruits.remove(function(v) {
  return chosenFruit().indexOf(v) == -1;
});

console.log(allFruits())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>