使用Ramda从数组数组中删除数组?

时间:2017-11-19 22:30:15

标签: javascript arrays ramda.js

是否有使用Ramda库从数组数组中删除数组的简写选项?

Items to remove: [[1, 2], [a, b]]
Remove from: [[g, d], [5, 11], [1, 2], [43, 4], [a, b]]

Result: [[g, d], [5, 11], [43, 4]]

5 个答案:

答案 0 :(得分:2)

R.rejectR.eitherR.equals的组合可以达到此目的。



const data = [['g', 'd'], [5, 11], [1, 2], [43, 4], ['a', 'b']]

const fn = R.reject(R.either(R.equals(['a', 'b']), R.equals([1, 2])))

console.log(fn(data))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

R.difference使用R.flip

&#13;
&#13;
pe:documentViewer
&#13;
const data = [['g', 'd'], [5, 11], [1, 2], [43, 4], ['a', 'b']]
const itemsToRemove = [[1, 2], ['a', 'b']]

const fn = R.flip(R.difference)(itemsToRemove);

console.log(fn(data))
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用vanilla JavaScript,您可以复制两个数组中的每一个,.map()返回数组元素的string表示。

然后循环遍历可移动项目数组,并使用indexOf()检查复制数组中每个项目是否存在。

这应该是你的代码:

var arr = [["g", "d"], [5, 11], [1, 2], [43, 4], ["a", "b"]];
var strArr = arr.map(function(a){
    return a.join(",");
});
 var toRemove = [[1, 2], ["a", "b"]];
 var strToRemove = toRemove.map(function(el){
    return el.join(",");
 });

strToRemove.forEach(function(a){
    if(strArr.indexOf(a)>-1){
        arr.splice(strArr.indexOf(a), 1);
        strArr.splice(strArr.indexOf(a), 1);
    }
});

<强>演示:

&#13;
&#13;
var arr = [
  ["g", "d"],
  [5, 11],
  [1, 2],
  [43, 4],
  ["a", "b"]
];
var strArr = arr.map(function(a) {
  return a.join(",");
});
var toRemove = [
  [1, 2],
  ["a", "b"]
];
var strToRemove = toRemove.map(function(el) {
  return el.join(",");
});

strToRemove.forEach(function(a) {
  if (strArr.indexOf(a) > -1) {
    arr.splice(strArr.indexOf(a), 1);
    strArr.splice(strArr.indexOf(a), 1);
  }
});
console.log(arr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这可能是最好的答案

使用R.rejectR.contains

var Itemstoremove =  [[1, 2], [a, b]]
var Removefrom =  [[g, d], [5, 11], [1, 2], [43, 4], [a, b]]

var Result = R.reject(R.contains(R.__, Itemstoremove), Removefrom)

console.log(Result)

答案 4 :(得分:0)

只需使用以下代码行:

const data = [
  ['g', 'd'],
  [5, 11],
  [1, 2],
  [43, 4],
  ['a', 'b']
]
const itemsToRemove = [
  [1, 2],
  ['a', 'b']
];

console.log(R.difference(data, itemsToRemove));