Array.push() if does not exist?

For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf() and if it doesn’t then just push the item into the array: var newItem = “NEW_ITEM_TO_ARRAY”; var array = [“OLD_ITEM_1”, “OLD_ITEM_2”]; array.indexOf(newItem) === -1 ? array.push(newItem) : console.log(“This item already exists”); console.log(array)

Using C# to check if string contains a string in string array

Here’s how: using System.Linq; if(stringArray.Any(stringToCheck.Contains)) /* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */ This checks if stringToCheck contains any one of substrings from stringArray. If you want to ensure that it contains all the substrings, change Any to All: if(stringArray.All(stringToCheck.Contains))

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.16). You also have the option to leave it with a nil value: var myslice []int As written in the Golang.org blog: a nil slice is functionally equivalent to a zero-length slice, even though … Read more

How to get last key in an array?

A solution would be to use a combination of end and key (quoting) : end() advances array ‘s internal pointer to the last element, and returns its value. key() returns the index element of the current array position. So, a portion of code such as this one should do the trick : $array = array( … Read more

How to find first element of array matching a boolean condition in JavaScript?

Since ES6 there is the native find method for arrays; this stops enumerating the array once it finds the first match and returns the value. const result = someArray.find(isNotNullNorUndefined); Old answer: I have to post an answer to stop these filter suggestions 🙂 since there are so many functional-style array methods in ECMAScript, perhaps there’s … Read more

How can I loop through enum values for display in radio buttons? [duplicate]

Two options: for (let item in MotifIntervention) { if (isNaN(Number(item))) { console.log(item); } } Or Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key]))); (code in playground) Edit String enums look different than regular ones, for example: enum MyEnum { A = “a”, B = “b”, C = “c” } Compiles into: var MyEnum; (function (MyEnum) { MyEnum[“A”] = “a”; MyEnum[“B”] … Read more