объект и массив фильтра javascript - PullRequest
0 голосов
/ 27 апреля 2018

Можете ли вы помочь мне отфильтровать эти данные?

var arr = {
    "data": [
        {
            "name": "a",
            "tags": [1,2,3,4],
        },
        {
            "name": "b",
            "tags": [5,6,7,8],
        },
    ]
};
var filter = {
    "tags" : [6,7]
};

var res = 'result';

console.log(arr.data);
console.log(filter);
console.log(res);

Как я могу получить отфильтрованный результат? Спасибо

1 Ответ

0 голосов
/ 27 апреля 2018

Поскольку Array.filter - это функция, которая принимает функцию, я привожу пример того, как можно использовать функции более высокого порядка (функции, которые принимают функции и / или возвращают функции).

Функции, которые возвращают функции, используют то, что называется каррированием / закрытием, и могут применяться частично (например, const plus = a=>b=>a+b; const plusTen=plus(10); const eleven=plusTen(1).

Вот пример.

const arr = [
  {
    "name": "a",
    "tags": [1, 2, 3, 4],
  },
  {
    "name": "b",
    "tags": [5, 6, 7, 8],
  },
];

//function to get an item from an object (in this case tags)
//  defaults to empty array if o or o.tags doesn't exist
const getTags = o => (o&&o.tags) || []; 

//function to compare a value, in this case array of numbers (haystack)
//  contains all of the array of number (needles)
//  in this case the haystack is tags and needles are the values we are looking for
//  returns true if all the needles are in the haystack or false if one needle is not found
const compareAllPrimitive = (hayStack,needles) =>
  needles.reduce(
    (all,needle)=>
      (all)
        ? hayStack.includes(needle)
        : all
    ,true
  );
//similar to compareAllPrimitive but will return true if any of needle(s) are found in the 
//  haystack
const compareSomePrimitive = (hayStack,needles) =>
  needles.reduce(
    (all,needle)=>
      (all)
        ? hayStack.includes(needle)
        : all
    ,false
  );
//curryable function to filter, takes 2 functions:
//  getter: to get the value to compare from the object passed into it 
//    like getTags to get tags from an item
//  comparer: to compare the value 
const filterFn = getter => comparer => object =>
  //in this case the comparer will be a partially applied function that 
  //  takes needles and haystack: needles => haystack => needles in haystack
  //  the function will already contain needles when passed in so only needs
  //  haystack to return true or false
  comparer(getter(object))
//partially applied filterFn getting the tags property from an object
const filterTags = filterFn(getTags);
//curryable function to see if all tagsToFind are in allTags
const compareAllTags = tagsToFind => allTags =>
  compareAllPrimitive(allTags,tagsToFind);
//partially applied filterFn that has getter and comparer, only need to pass the object in
const hasAllTags = whatTags=>filterTags(compareAllTags(whatTags));

//use hasAllTags filter function
console.log(
  "has all [1,2]",
  //array filer takes a function as argument, details can be found here:
  //https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
  arr.filter(hasAllTags([1,2]))
);

//partially applied filterFn that has getter and comparer, only need to pass the object in
const hasSomeTags = whatTags=>
  filterTags(
    tagsToFind => allTags =>//can pass in a function without assigning it to a constant first
      compareSomePrimitive(allTags,tagsToFind)
  );
//use hasSomeTags filter function
console.log(
  "has some [1,5]",
  arr.filter(hasSomeTags([1,5]))
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...