简体   繁体   中英

Remove array from array of arrays using Ramda?

Is there any shorthand option to remove array from array of arrays using Ramda library ?

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]]

Use R.difference with R.flip :

 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))
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

A combination of R.reject , R.either and R.equals can achieve this.

 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>

This is probably the best answer

use R.reject and R.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)

With vanilla JavaScript, you can make a copy of each of your two arrays, with .map() returning a string representation of your array elements.

Then loop over your removable items array and check with indexOf() over the existence of each item in your copied array.

This is how should be your code:

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);
    }
});

Demo:

 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);

Just use following lines of code:

 const data = [ ['g', 'd'], [5, 11], [1, 2], [43, 4], ['a', 'b'] ] const itemsToRemove = [ [1, 2], ['a', 'b'] ]; console.log(R.difference(data, itemsToRemove));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM