Get Index of Object from Array of Dictionary with Key Value

How to get index of dictionary from an array of dictionary?

Maybe better use array of tuples

var array: [(txt: String, value: Int)] = [
("5mbps", 2048),
("50mbps", 18048),
("55mbps", 22048)
]

Swift 2.3

array.filter { element in
return element.txt == findingText
}.first?.value

Swift 3

array.first { element in
return element.txt == findingText
}?.value

Get index of object from array of dictionary with key value

Here is what you should be doing after using a json parser

 let array:NSArray = [
[
"Id": 20130,
"IsNew": 1,
"Title":"Behaviour"
],
[
"Id": 20180,
"IsNew": 1,
"Title":"Result"
]]

let k = array as Array
let index = k.indexOf {
if let dic = $0 as? Dictionary<String,AnyObject> {
if let value = dic["Title"] as? String
where value == "Result"{
return true
}
}
return false
}

print(index) // index

Get Index of a Dictionary from an array of Dictionaries for a given Key and Value

You can use following LINQ query which is like a single loop that breaks as soon as possible:

int index = dictionaries
.Select((dict, index) => (dict, index)) // put the dictionary and it's index in a ValueTuple
.Where(x => x.dict.Any(kv => kv.Key == "Key2" && kv.Value == "ValueD")) // filter by key & value
.Select(x => x.index) // select the index
.DefaultIfEmpty(-1) // if no dictionary met the condition you want -1 as result
.First(); // this is safe, you get either a single index or -1 as fallback

but note that you are losing the fast lookup capabilities of a dictionary with your approach.

Edit: Somebody's approach is more efficient, you can combine it with this:

int index = dictionaries
.Select((dict, index) => (dict, index)) // put the dictionary and it's index in a ValueTuple
.Where(x => x.dict.TryGetValue("Key2", out string value) && value == "ValueD") // filter by key & value
.Select(x => x.index) // select the index
.DefaultIfEmpty(-1) // if no dictionary met the condition you want -1 as result
.First(); // this is safe, you get either a single index or -1 as fallback

Javascript How to find the index of an object, of an array of dictionaries, by a given key and value

If you are not building a function that accepts a query expression, Array.findIndex should be sufficient.

const arr = [{
'key1': 'valueA',
'key2': 'valueB',
'key3': 'valueC'
},
{
'key1': 'valueD',
'key2': 'valueE',
'key3': 'valueF'
}
]

const idx = arr.findIndex(({ key2 }) => key2 === 'valueE');

console.log(idx)

How to find index of an object by key and value in an javascript array

The Functional Approach

All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for and each loops that have been proposed thus far and with ES6 syntax it is quite elegant.

Update

There's now a great way of doing this called findIndex which takes a function that return true/false based on whether the array element matches (as always, check for browser compatibility though).

var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
});

With ES6 syntax you get to write this:

var index = peoples.findIndex(p => p.attr1 == "john");


The (Old) Functional Approach

TL;DR

If you're looking for index where peoples[index].attr1 == "john" use:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

Explanation

Step 1

Use .map() to get an array of values given a particular key:

var values = object_array.map(function(o) { return o.your_key; });

The line above takes you from here:

var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];

To here:

var values = [ "bob", "john", "larry" ];

Step 2

Now we just use .indexOf() to find the index of the key we want (which is, of course, also the index of the object we're looking for):

var index = values.indexOf(your_value);

Solution

We combine all of the above:

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");

Or, if you prefer ES6 syntax:

var index = peoples.map((o) => o.attr1).indexOf("john");


Demo:

var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];

var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
console.log("index of 'john': " + index);

var index = peoples.map((o) => o.attr1).indexOf("larry");
console.log("index of 'larry': " + index);

var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");
console.log("index of 'fred': " + index);

var index = peoples.map((o) => o.attr2).indexOf("pizza");
console.log("index of 'pizza' in 'attr2': " + index);

How do I access the index of items inside an array that is inside a dictionary?

I think you meant to write:

for key in mydict:
for i, x in enumerate(my_dict[key][2]):
#other code here

get index of dictionary from array of dictionary in swift?

You can use firstIndex(where:) and pass a closure to it:

arrayOfDicts.firstIndex(where: { $0.keys.contains("Twitter2")})

Or more generally with key:

arrayOfDicts.firstIndex(where: { $0.keys.contains(key)})

Get index of item in dictionary by key in Swift

If I understand you correctly, you could do it like so:

let myList = [
2: "Hello",
4: "Goodbye",
8: "Whats up",
16: "Hey"
]

let index = Array(myList.keys).index(of: property.propertyValue)

And then to find the key you're looking for again...

let key = Array(myList.keys)[index!]

As said in other answers, a dictionary is probably not the data structure you're looking for. But this should answer the question you've asked.

Get index of a key/value pair in a C# dictionary based on the value

There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).

Obviously you can get the key from a KeyValuePair just by using the Key property, so that will let you use the indexer of the dictionary:

var pair = ...;
var value = dictionary[pair.Key];
Assert.AreEqual(value, pair.Value);

You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:

var key = dictionary.Where(pair => pair.Value == desiredValue)
.Select(pair => pair.Key)
.FirstOrDefault();

key will be null if the entry doesn't exist.

This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.

Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.



Related Topics



Leave a reply



Submit