I have an array of people\'s names along with their knowledge of languages. What I want to do is pass a filter onto the language column and filter out any results that don\'
To me it seems like you're making it a little too complicated.
filter
, for
loop, for in
loop).for in
loop for an array.new Array
and [...]
.I updated it a little and it looks like this is what you want: http://jsfiddle.net/pimvdb/RQ6an/.
var myArray = [["Steppen", "Spanish Polish"],
["Wolf", "Spanish Polish Tagalog"],
["Amanda", "Spanish"],
["Ada", "Polish"],
["Rhonda", "Spanish Tagalog"]];
var userPassedFilter = ["Tagalog"];
newArray = consolidatedFilters(myArray, userPassedFilter);
console.log(newArray);
function consolidatedFilters(passedArray, passedFilter) {
var filteredArray = passedArray.filter(
function(el) { // executed for each person
for (var i = 0; i < passedFilter.length; i++) { // iterate over filter
if (el[1].indexOf(passedFilter[i]) != -1) {
return true; // if this person knows this language
}
}
return false;
}
);
return filteredArray;
}
this is the ultimate solution in the ES6 way: No need to Search the same query again in another thread.
var array1 = ['a', 'b', 'c', 'd', 'e'];
var array2 = ['b', 'd', 'f'];
array1 = array1.filter(function(item) {
return !array2.includes(item);
})
console.log(array1); // [ 'a', 'c', 'e' ]
console.log(array2); // [ 'b', 'd', 'f' ]
Another answer to @millerjay response
function destroyer(arr) {
var array = arr;
var filterArray = Array.from(arguments).slice(1);
var filtered = arr.filter(function(val){
return filterArray.indexOf(val) === -1;
});
return filtered;
}
destroyer([1, 2, 3, 1, 2, 3], 3, 2);
//prints [1,1]
I'm new to javascript and this is the only way I was able to filter an array with another array which made sense to me:
function filterThisByThis(arr) {
var numArgs = arguments.length;
var newArr = [];
for (var i = 1; i < numArgs; i ++) {
newArr.push(arguments[i]);
} // makes a new array from all arguments parsed to fuction minus the orginal array
arr = arr.filter(function(val) {
for (var j = 0; j < newArr.length; j++) {
if (val == newArr[j]) {
return false;}
}
return true;
}); // uses the filter function to iterate over the orginal array taking out all values which occur in the new array
return arr;
}
filterThisByThis([1, 2, 3, 4, 1, 2, 3, 4], 1, 3);
// prints [2, 4, 2, 4]
here is a more generic version that removes all elements that are in the filter array
function destroyer(arr) {
// Remove all the values
var passedArray = arr;
var passedFilter = Array.prototype.slice.call(arguments, 1);
var newArray = passedArray.filter(function(x){
if(passedFilter.indexOf(x) !== -1){
return false;
}
return true;
});
return newArray;
}
destroyer([1, 2, 3, 1, 2, 3], 3, 2);
//prints [1,1]