var array = [ "123-foo", "456-bar", "789-baz" ];
var selected = [ "123", "789" ];
var partition_contains = _.partition(array, function(value){
return _.contains(selected, value);
});
console.log(partition_contains);
var partition_filter = _.partition(array, function(value){
return !!_.filter(selected, function(s){ return value.indexOf(s) !== -1; }).length;
});
console.log(partition_filter);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
The output is:
[
[],
[
"123-foo",
"456-bar",
"789-baz"
]
]
Expected output:
[
[
"123-foo",
"789-baz"
],
[
"456-bar"
]
]
Why doesn't contain work as I expect although internally its using indexOf
?
Edit: Works with filter
but wonder why not contains?
From first approach, I think it is because _.contains
match exact value between array and the targeted value.
console.log(_.contains(selected, "123-foo")); // false
My solution will use some
method from Array.
var partitioned = _.partition(array, value => selected.some(select => value.indexOf(select) > -1));
console.log(partitioned);
I saw underscore.js also has _.some
method.