For given array ,find indexs of each occurances of each element in array.
e.g.
Input is ["A", "B", "B", "C", "A", "A"]
Output should be
[
{ element: 'A', occurenceIndexes: [ 0, 4, 5 ] },
{ element: 'B', occurenceIndexes: [ 1, 2 ] },
{ element: 'C', occurenceIndexes: [ 3 ] }
]
Code:
let myArr = ["A", "B", "B", "C", "A", "A"];
function findAllIndices(myArr) {
let indexOfAllElements = [];
for (let i = 0; i < myArr.length; i++) {
let startIndex = 0;
let indexsOfAnElement = [];
let visited = indexOfAllElements.map((m) => {
return m.element;
});
if (visited.includes(myArr[i])) {
continue;
} else {
//for given elemment in array find indexes at which that element occurs in array
while (startIndex < myArr.length) {
let indexOfElement = myArr.findIndex((element, currentIndex) => {
if (currentIndex < startIndex) {
currentIndex++;
} else {
if (element == myArr[i]) {
startIndex = currentIndex + 1;
return true;
}
}
if (currentIndex == myArr.length) {
return false;
}
});
if (indexOfElement == -1) {
break;
} else {
indexsOfAnElement.push(indexOfElement);
}
}
indexOfAllElements.push({
element: myArr[i],
occurenceIndexes: indexsOfAnElement,
});
}
}
return indexOfAllElements
}
let foundAllIndices = findAllIndices(myArr)
console.log(foundAllIndices)
Output:
[
{ element: 'A', occurenceIndexes: [ 0, 4, 5 ] },
{ element: 'B', occurenceIndexes: [ 1, 2 ] },
{ element: 'C', occurenceIndexes: [ 3 ] }
]
No comments:
Post a Comment