I think that you are using the wrong indexOf method. It looks like you are using the String.prototype.indexOf() rather than Array.prototype.indexOf().
This should work for your code, but it is hard to test without any data.
const a = ['Sally', 'Walker', 'Claire', 'Lilly'];
const b = ['Kyle', 'Sally', 'Walker', 'Caroline', 'Claire'];
const d_hash = {};
const d_list = [];
a.forEach(a => {
const i = b.indexOf(a);
if (i === -1) {
// the name is missing
d_hash[a] = {
status: 'missing',
index: null
};
d_list.push(a);
} else {
// the name has been found
d_hash[a] = {
status: 'found',
index: i
}
}
});
console.log(d_hash);
console.log(d_list);
The logic:
- I have two arrays of names, array
a
and array b
. I want to find the names that appear in a
but not in b
.
- For each value of a, try to find the index of the element in b. If the index is -1, we know the element could not be found.
- Store the results as a hash and also the list of names that could not be found in an array.
- JS Bin
Alternatively
What you are really wanting the do is find the difference of Set a
and Set b
.
We can convert each array to a set and then perform a difference to get the elements that appear in one but not the other.
const a = ['Sally', 'Walker', 'Claire', 'Lilly'];
const b = ['Kyle', 'Sally', 'Walker', 'Caroline', 'Claire'];
const set_a = new Set(a);
const set_b = new Set(b);
// code adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
Set.prototype.diff = function (b) {
const d = new Set(a);
b.forEach(el => d.delete(el));
return d;
}
console.log(Array.from(set_a.diff(set_b))); // ["Lilly"]
Clarifications:
For each is a method natively provided on the Array.prototype in newer browsers. More info here.
forEach should be applied to an array, and the method expects a function callback that should handle each element.
- What is
(...) => { ... }
?
This represents arrow functions which are available in ES6. This arrow syntax provides an alternative (and in my opinion, cleaner and clearer) way to define functions.
Something that which was previously represented as:
function (el) {
d.delete(el);
}
Can be shortened to
(el) => d.delete(el);