How to Find Index of All Occurrences of Element in Array

How to find index of all occurrences of element in array?

The .indexOf() method has an optional second parameter that specifies the index to start searching from, so you can call it in a loop to find all instances of a particular value:

function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
}

var indexes = getAllIndexes(Cars, "Nano");

You don't really make it clear how you want to use the indexes, so my function returns them as an array (or returns an empty array if the value isn't found), but you could do something else with the individual index values inside the loop.

UPDATE: As per VisioN's comment, a simple for loop would get the same job done more efficiently, and it is easier to understand and therefore easier to maintain:

function getAllIndexes(arr, val) {
var indexes = [], i;
for(i = 0; i < arr.length; i++)
if (arr[i] === val)
indexes.push(i);
return indexes;
}

How to find all occurrences of an element in a list

You can use a list comprehension with enumerate:

indices = [i for i, x in enumerate(my_list) if x == "whatever"]

The iterator enumerate(my_list) yields pairs (index, item) for each item in the list. Using i, x as loop variable target unpacks these pairs into the index i and the list item x. We filter down to all x that match our criterion, and select the indices i of these elements.

Finding indices for all instances of element in array

You can create your own indices method that takes a predicate as parameter:

Xcode 11 • Swift 5.1

extension Collection where Element: Equatable {
func indices(of element: Element) -> [Index] { indices.filter { self[$0] == element } }
}

extension Collection {
func indices(where isIncluded: (Element) throws -> Bool) rethrows -> [Index] { try indices.filter { try isIncluded(self[$0]) } }
}

let arr = [1, 2, 3, 1, 0, 1, 2, 2, 3, 1, 1, 2]
let search = 1

let indices = arr.indices(where: { $0 == search })
// or simply
// let indices = arr.indices { $0 == search }
print(indices) // [0, 3, 5, 9, 10]

let indices2 = arr.indices(of: search)
print(indices2) // [0, 3, 5, 9, 10]

let string = "Hello World !!!"
let indices3 = string.indices(of: "o")
print(indices3) // [Swift.String.Index(_compoundOffset: 16, _cache: Swift.String.Index._Cache.character(1)), Swift.String.Index(_compoundOffset: 28, _cache: Swift.String.Index._Cache.character(1))]

How can i get the indexes of all the occurrences of an element in a list through recursion?

The problem with your code is that you are creating a new list object each time you recursively call the function, since you are doing list = [] each time. (By the way, do not name a variable list, it is already a reserved keyword in Python that denotes the list type, here you can use indices_found for example)

What you want to do is actually pass down the same list to every call of the function :

def allindex(
arr, idx, fsf, key, found_indices
): # arr=array, idx=index, fsf=found so far, key=key to be found
if idx == len(arr):
return found_indices
if arr[idx] == key:
found_indices.append(idx)
allindex(arr, idx + 1, fsf + 1, 8, found_indices)
return found_indices
else:
allindex(arr, idx + 1, fsf, 8, found_indices)
return found_indices

This correctly returns [3, 5, 7].

Find all occurrences of each element of an array in another array in Javascript

You'd just filter the first array based on the second array

var a = [1, 1, 2, 3, 4, 5, 5, 6, 7, 7];var b = [1, 2, 5];
var result = a.filter( z => b.indexOf(z) !== -1 );
console.log(result);

Get indices (indexes) of all occurrences of an element in an array

If you JUST have two elements you want to know the position for, you can use

indexOf() and lastIndexOf()

Find All elements / indexes in an array with predicate - Typescript

SOLUTION :

    /**
* Returns the indexes of all elements in the array where predicate is true, [] otherwise.
* @param array The source array to search in
* @param predicate find calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* it is added to indexes and the functions continue..
*/
findAllIndexes<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number[] {
const indexes = [];
let l = array.length;
while (l--) {
if (predicate(array[l], l, array)) {
indexes.push(l);
}
}
return indexes;
}

and to use it :

const myList = [0, 2, 1, 1, 3, 4, 1];
const indexes = this.findAllIndexes(myList, x => x === 1);
// return [6, 3, 2]

OTHER METHOD :

A little different but can be useful (allow to get all elements and not indexes) :

const myList = [0, 2, 1, 1, 3, 4, 1];
const allElements = myList.filter(x => x === 1);

PS : I chose to iterate the loop from the end to the beginning, it is possible to invert it to get [2, 3, 6] instead of [6, 3, 2].

Happy codding everyone !

Find the index number of the fourth occurrence in an array

This will do the trick for you:

function getFourthOccurance(number){
let ocurrences = 0;
for (i = 0; i <= array.length; i++){
if (array[i] === number){
ocurrences++;
if(ocurrences === 4){
return i;
}
}
}
}

let array = [0,4,4,3,2,1,4,5,6,4,6,9];
console.log("The fourth occurrence of 4 is:", getOccurance(4))

Using indexOf method on array, getting all indexes and not just first

You can use the builtin Array.prototype.forEach like this

var indices = [];

array.forEach(function(currentItem, index) {
if (currentItem === "test") {
indices.push(index);
}
});

console.log(indices);

Even better you can use Array.prototype.reduce like this

var indices = array.reduce(function(result, currentItem, index) {
if (currentItem === "test") {
result.push(index);
}
return result;
}, []);

console.log(indices);

Since you want the solution to be even working in IE, you might want to go with the plain old loop, like this

var indices = [], i;

for (i = 0; i < array.length; i += 1) {
if (array[i] === "test") {
indices.push(i);
}
}

console.log(indices);

How to find index of all occurrences of an element in array (Ramda.js way)?

@pierrebeitz's answer is on point, namely that when you need access to indices while iterating over a list you'll typically zip the list up along with its indices. Ramda provides an R.addIndex function for modifying functions like map to provide the index along with each element while iterating.

The nesting in his example can also be replaced with a composition pipeline if you prefer:

const zipWithIndex = addIndex(map)(pair);

const isHeaderOrFooter = either(equals('Header'), equals('Footer'));

const hfIndices = pipe(
zipWithIndex,
filter(pipe(head, isHeaderOrFooter)),
map(nth(1))
);

hfIndices(arr);

One thing to be mindful of with both of these approaches is you'll end up iterating over the list multiple times. This won't typically be a problem for a small list, however for larger lists you might want to consider using R.into which effectively fuses the maps and filter together into a transducer that will now take only a single pass over the list (see http://simplectic.com/blog/2015/ramda-transducers-logs/ for a good intro to transducers).

This can be achieved with a small tweak to hfIndices in the above example by swapping the composition from pipe to compose (transducer functions compose in the opposite order) and wrapping it with into.

const hfIndices = into([], compose(
zipWithIndex,
filter(pipe(head, isHeaderOrFooter)),
map(nth(1))
));


Related Topics



Leave a reply



Submit