1

I have two array available, selected which is having some values. I am having another array named finalAvailable in which I want all those from the available array at the same time also to remove those which are present in selected array. An example is shown below

var available = ["A", "B", "C", "D", "E"];
var selected = ["B", "C"];

so the finalAvailable array will be like

var finalAvailable = ["A", "D", "E"];

I have written a code for achieving this and its working fine, but the problem is since I am using Lo-dash within my project my team lead ask whether there is any function available to achieve this using Lo-dash, I searched but could find anything, I don't know whether I am missing anything.

Can anyone tell me whether there is anything similar available in Lodash

My code is as given below

var available = ["A", "B", "C", "D", "E"];
var selected = ["B", "C"];

var finalAvailable = [];

for (var i = 0; i < available.length; i++) {
    var flag = true;
    for (var j = 0; j < selected.length; j++) {
        if (available[i] == selected[j]) {
            flag = false;
        }
    }
    if (flag) {
        finalAvailable.push(available[i])
    }
}

2 Answers 2

3

Try this

var available = ["A", "B", "C", "D", "E"];
var selected = ["B", "C"];

var finalAvailable = _.filter(available, function (el) {
  return _.indexOf(selected, el) === -1    
});

console.log(finalAvailable);

// or you can use _.difference
console.log(_.difference(available, selected));
<script src="https://rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

Try without Lodash:

let available = ["A", "B", "C", "D", "E"];
let selected = ["B", "C"];

let finalAvailable = available.filter(item => selected.indexOf(item) === -1);
console.log(finalAvailable);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.