How to declare and add items to an array in Python?

{} represents an empty dictionary, not an array/list. For lists or arrays, you need []. To initialize an empty list do this: my_list = [] or my_list = list() To add elements to the list, use append my_list.append(12) To extend the list to include the elements from another list use extend my_list.extend([1,2,3,4]) my_list –> [12,1,2,3,4] … Read more

json_decode to array

As per the documentation, you need to specify true as the second argument if you want an associative array instead of an object from json_decode. This would be the code: $result = json_decode($jsondata, true); If you want integer keys instead of whatever the property names are: $result = array_values(json_decode($jsondata, true)); However, with your current decode … Read more

How to initialize an array in Java?

data[10] = {10,20,30,40,50,60,71,80,90,91}; The above is not correct (syntax error). It means you are assigning an array to data[10] which can hold just an element. If you want to initialize an array, try using Array Initializer: int[] data = {10,20,30,40,50,60,71,80,90,91}; // or int[] data; data = new int[] {10,20,30,40,50,60,71,80,90,91}; Notice the difference between the two … Read more

How do I check whether an array contains a string in TypeScript?

The same as in JavaScript, using Array.prototype.indexOf(): console.log(channelArray.indexOf(‘three’) > -1); Or using ECMAScript 2016 Array.prototype.includes(): console.log(channelArray.includes(‘three’)); Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn’t usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For … Read more

Get the index of the object inside an array, matching a condition

As of 2016, you’re supposed to use Array.findIndex (an ES2015/ES6 standard) for this: a = [ {prop1:”abc”,prop2:”qwe”}, {prop1:”bnmb”,prop2:”yutu”}, {prop1:”zxvz”,prop2:”qwrq”}]; index = a.findIndex(x => x.prop2 ===”yutu”); console.log(index); It’s supported in Google Chrome, Firefox and Edge. For Internet Explorer, there’s a polyfill on the linked page. Performance note Function calls are expensive, therefore with really big arrays … Read more

Convert object array to hash map, indexed by an attribute value of the Object

This is fairly trivial to do with Array.prototype.reduce: var arr = [ { key: ‘foo’, val: ‘bar’ }, { key: ‘hello’, val: ‘world’ } ]; var result = arr.reduce(function(map, obj) { map[obj.key] = obj.val; return map; }, {}); console.log(result); // { foo:’bar’, hello:’world’ } Note: Array.prototype.reduce() is IE9+, so if you need to support older … Read more