I have an array of names which all have duplicates.
let arr = ['John', 'Jack', 'John', 'Jack', 'Jack', 'June', 'June'];
I want to create a new array with some of the duplicate elements, specifying an instance at which they occur.
For example, I may want the array to contain only the second occurrence of John, Jack and June. The array will look like this:
'John', 'Jack', 'June'
To accomplish this, I have declared an object ni
and looped through arr
to add properties to the object corresponding to each name; the property will hold the value of an array containing each index at which the name occurs.
let ni = {};
for(let i = 0; i < arr.length; i++) {
let name = arr[i];
if(nc.hasOwnProperty(name)) {
ni[name].push(i);
} else {
ni[name] = [i];
}
}
console.log(ni);
// > Object { John: Array [0, 2], Jack: Array [1, 3, 4], June: Array [5, 6] }
In my Array.filter function, I check if the element's index is equal to index 1 of the object property corresponding to the same name.
let newArr = arr.filter(function(name) {
if(ni.hasOwnProperty(name)) {
return arr.indexOf(name) === ni[name][1];
}
});
This should return John
at index 2
, Jack
at index 3
, and June
at index 6
to the new array.
However, this has not worked. Logging newArr
to the console will output an array completely unchanged from the original.
> Array ["John", "Jack", "John", "Jack", "Jack", "June", "June"]