Array Index Of

From SwiftAPI

Jump to: navigation, search

Contents

C++

#include <algorithm>
using namespace std;
 
int haystack[] = { 9, 3, 8, 5, 8, 7 };
int needle = 8;
int *iter = find(haystack, haystack+6, needle);
// iter == haystack + 2

C#

List<int> haystack = new List<int>() { 9, 3, 8, 5, 8, 7 };
int needle = 8;
int pos = haystack.IndexOf(needle);
// pos == 2

Java

for Lists:

import java.util.Arrays;
 
List<Integer> haystack = Arrays.asList( 9, 3, 8, 5, 8, 7 );
Integer needle = 8;
int pos = haystack.indexOf(needle);
// pos == 2

for arrays of objects (not primitive arrays):

import java.util.Arrays;
 
Integer[] haystack1 = { 9, 3, 8, 5, 8, 7 };
List<Integer> haystack = Arrays.asList( haystack1 );
Integer needle = 8;
int pos = haystack.indexOf(needle);
// pos == 2

JavaScript

JavaScript 1.6+, Prototype, MooTools

Firefox 1.5+

developer.mozilla.org prototype mootools

var haystack = [9, 3, 8, 5, 8, 7];
var needle = 8;
var pos = haystack.indexOf(needle);
// pos == 2

jQuery

jquery

var haystack = [9, 3, 8, 5, 8, 7];
var needle = 8;
var pos = $.inArray(needle, haystack);
// pos == 2

JavaScript 1.5 and below

var haystack = [9, 3, 8, 5, 8, 7];
var needle = 8;
var pos = -1;
var length = haystack.length;
for(var i = 0; i < length && pos == -1; i++) {
    if(haystack[i] == needle) {
        pos = i;
    }
}
// pos == 2

Objective-C

developer.apple.com

- (NSUInteger)indexOfObject:(id)anObject
NSArray *haystack = @[@9, @3, @8, @5, @8, @7];
id needle = @8;
int pos = [haystack indexOfObject:needle];
// pos == 2

Perl

use List::Util qw(first);
@haystack = (9, 3, 8, 5, 8, 7);
$needle = 8;
$pos = first {$haystack[$_] eq $needle} (0..$#haystack);
# $pos === 2

PHP

php.net

mixed array_search ( mixed $needle , array $haystack [, bool $strict ] )
$haystack = array(9, 3, 8, 5, 8, 7);
$needle = 8;
$pos = array_search($needle, $haystack);
// $pos === 2

Python

docs.python.org

list.index(x)
haystack = [9, 3, 8, 5, 8, 7]
needle = 8
pos = haystack.index(needle)
# pos == 2

Ruby

ruby-doc.org

array.index(obj) => int or nil
haystack = [9, 3, 8, 5, 8, 7]
needle = 8
pos = haystack.index(needle)
# pos == 2

Swift

let haystack = [9, 3, 8, 5, 8, 7]
let needle = 8
let pos = find(haystack, needle)
// pos == Optional(2)
Personal tools