Programming language cheat sheets for 20+ languages. Strings [StrJoin/String] Mathematics Operators and Symbols General (Control Flow/Debugging) [PrintKeyValueXXX, ForEachPrintDemo, classes] Dates Objects New Features Timelines Documentation Links Sections: Any Methods Array Methods (Array/List/Vector) Map Methods (Map/Dictionary) Object Methods (Object/Struct) Range Methods Tuple Methods (Tuple/Entry/Pair/Triple) Optional Methods (Optional/Option/Nullable) Set Methods JSON Methods Array.ForEach Demo Functions Array.Map Demo Functions Array.Reduce Demo Functions Array.Filter Demo Functions Import/Include Tips Language-Specific Notes Language-Specific Notes: SQL: Temporary Variable One-Liners (MySQL/PostgreSQL/SQLite) Language-Specific Notes: SQL: Settings (MySQL/PostgreSQL/SQLite) Language-Specific Notes: Java: Function Objects Note: UFL: Universal Function Library, a set of around 100-300 standard functions for all programming languages. Languages do not have to implement anything exactly to the UFL specification, it is a guide.
UFL: Any.Type [object type: name only][see also: PrintType] AutoHotkey: Type(oObj) [also: ObjGetBase()/ObjSetBase()] C++: ___ [can use: force a deliberate error, e.g. "" * oObj;] [e.g. '123 * "abc"' gives 'error: invalid operands to binary expression ('int' and 'const char[4]')'] [also: typeid(oObj).name()] [e.g. int has typeid 'i'] [note (typeid): return values can be cryptic] [also (for GCC / Clang compilers): #define PRINTVARTYPE(v) { char * name = abi::__cxa_demangle(typeid(v).name(), 0, 0, 0); std::cout << #v << ": " << name << "\n"; free(name); }] [requires (abi): #include <cxxabi.h>] [MAJOR WARNING: compiler error messages and abi::__cxa_demangle() may give different results, e.g. whitespace differences: 'int[]'/'int []' and 'int *'/'int*'] C#: oObj.GetType().Name [also (for types, not variables): typeof() e.g. typeof(int)] Crystal: ___ [can use: oObj.class.name.split("::").last] Excel: =TYPE(A1) [also: =ERROR.TYPE(A1)] Excel VBA: TypeName(oObj) [also: TypeOf operator (which works on objects, but not primitives)] Go: fmt.Sprintf("%T", oObj) [also: fmt.Printf("%T\n", oObj)] Java: oObj.getClass().getSimpleName() [WARNING: doesn't work on primitives] [also (for types, not variables): .class e.g. int.class] JavaScript: typeof oObj [also (full name): Object.prototype.toString.call(oObj)] Kotlin: oObj::class.simpleName [note: throws if var of nullable type, e.g. throws on 'Any?', works on 'Any'] [also: oObj!!::class.simpleName] PHP: gettype($oObj) [also (for objects): get_class($oObj)] Python: type(oObj).__name__ R: typeof(oObj) [also: class()/mode()/storage.mode()] [also: is.vector()/is.list()/length()] [also (identify class type): is.object(oObj)/isS4(oObj)/is(oObj, "refClass")] [note: is.object() returns TRUE for S3/S4/reference classes] [WARNING: isS4() returns TRUE for S4 *and reference* classes] [WARNING: typeof(1) and typeof(c(1,2)) both return 'double'] [WARNING: length() returns the vector length, nchar() returns the string length] Ruby: ___ [can use: oObj.class.name.split("::").last] Rust: ___ [can use (full name): type_name_of_val(&oObj)] [requires: use std::any::type_name_of_val] Scala: oObj.getClass().getSimpleName() SQL (MySQL): ___ [can use: CREATE TEMPORARY TABLE MyTempTable SELECT 123; DESC MyTempTable;] [also (table info, doesn't list temporary tables): SELECT table_name,column_name,data_type,column_type FROM information_schema.columns WHERE instr(table_name, 'mytable')] SQL (PostgreSQL): pg_typeof(MyCol) [also (table info): SELECT table_name,column_name,data_type FROM information_schema.columns WHERE strpos(table_name, 'mytable')::bool] [WARNING: table_name appears to require lower case] [also: json_typeof(), jsonb_typeof()] SQL (SQLite): typeof(MyCol) [also: type FROM json_each(json_quote(MyCol))] [also (table info): SELECT * FROM sqlite_master] [also (table info): PRAGMA table_info(MyTable)] [also (table info): SELECT * FROM pragma_table_info('MyTable')] Swift: String(describing:type(of:oObj)) UFL: Any.TypeFull [object type: full name] AutoHotkey: Object.Prototype.ToString.Call(oObj) C++: ___ [can use: typeid(oObj).name()] C#: oObj.GetType().FullName Crystal: oObj.class.name Excel: ___ Excel VBA: ___ Go: fmt.Sprintf("%T", oObj) Java: oObj.getClass().getName() [WARNING: doesn't work on primitives] [also (for types, not variables): .class e.g. int.class] [note: '[I'/'[D' for int/double arrays respectively] JavaScript: Object.prototype.toString.call(oObj) Kotlin: oObj::class.qualifiedName [note: throws if var of nullable type, e.g. throws on 'Any?', works on 'Any'] [also: oObj!!::class.qualifiedName] PHP: ___ [can use: gettype($oObj)] [also (for objects): get_class($oObj)] Python: type(oObj) R: typeof(oObj) [also: class()/is.vector()/is.list()/length()] Ruby: oObj.class.name Rust: type_name_of_val(&oObj) [requires: use std::any::type_name_of_val] Scala: oObj.getClass().getName() [note: '[I'/'[D' for int/double arrays respectively] SQL (MySQL): ___ [can use: CREATE TEMPORARY TABLE MyTempTable SELECT 123; DESC MyTempTable;] [also (doesn't list temporary tables): SELECT data_type FROM information_schema.columns WHERE table_name = 'mytable'] SQL (PostgreSQL): pg_typeof(MyCol) [also: SELECT data_type FROM information_schema.columns WHERE table_name = 'mytable'] [WARNING: table_name appears to require lower case] [also: json_typeof(), jsonb_typeof()] SQL (SQLite): typeof(MyCol) Swift: String(reflecting:type(of:oObj)) UFL: (Any.TypeCustom) [object type: name only][custom function/macro 'mytype' to get the object type] AutoHotkey: mytype := Type [can use: Type(vVar)] C++: #define mytype(vVar) typeid(vVar).name() [note: a custom macro] C#: public static String mytype<T>(T vVar) {return vVar.GetType().Name;} Crystal: def mytype(vVar); vVar.class.name; end Excel: ___ [can use: =TYPE(A1)] [also: =ERROR.TYPE(A1)] Excel VBA: ___ [can use: TypeName(vVar)] Go: func mytype[T any](vVar T) string { return fmt.Sprintf("%T", vVar) } Java: public static <T> String mytype(T vVar) {return vVar.getClass().getSimpleName();} [WARNING: doesn't work on primitives] JavaScript: mytype = vVar => typeof vVar Kotlin: val mytype = {vVar: Any -> vVar::class.simpleName} PHP: ___ [can use: gettype($vVar)] Python: mytype = lambda vVar : type(vVar).__name__ R: mytype = typeof [also: mytype = class] Ruby: def mytype(vVar); vVar.class.name; end Rust: fn mytype<T>(_: T) -> &'static str {std::any::type_name::<T>()} Scala: var mytype = (vVar:Any) => vVar.getClass().getSimpleName() [WARNING: doesn't work on nulls] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: pg_typeof(MyCol)] SQL (SQLite): ___ [can use: typeof(MyCol)] Swift: var mytype: (_ vVar: Any) -> String = {vVar in String(describing:type(of:vVar))} UFL: (Any.TypeDefaultValueDemo) [return the default value for a type][this often returns a 'falsy' value][e.g. bool/int/float/string, typically false/0/0.0/"" respectively, also, the default for string is often null] AutoHotkey: ___ C++: ___ C#: var vValue = Array.Find((int[])[], v=>false) [note: Find() returns the array's default value if no match (e.g. 0 for ints, null for strings)] Crystal: ___ Excel: ___ Excel VBA: ___ Go: vValue := new([1]int)[0] Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: var vValue: Int = _ [note: using '_' assigns the default value for that type (e.g. 0 for ints, null for strings)] SQL (MySQL): ___ [can use: SELECT DEFAULT(v) FROM (SELECT 123 AS v) oTemp] [e.g. specify an arbitrary int, e.g. 123, it returns 0] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Any.IsTypeDemo [or VarIsTypeDemo][check if variable is of a certain type, using 'string' as an example][see also: IsString] AutoHotkey: ___ [e.g. vVar is String] [note: AHK v2 onwards] C++: ___ [e.g. std::is_same<decltype(vVar),std::string>::value] C#: ___ [e.g. vVar is String] Crystal: ___ [e.g. vVar.is_a? String] Excel: ___ Excel VBA: ___ [e.g. TypeName(vVar) = "String"] Go: ___ [e.g. fmt.Sprintf("%T", vVar) == "string"] Java: ___ [e.g. ((Object)vVar).getClass().equals(String.class)] JavaScript: ___ [e.g. typeof vVar == "string"] Kotlin: ___ [e.g. vVar is String] PHP: ___ [e.g. gettype($vVar) == "string"] Python: ___ [e.g. isinstance(vVar, str)] [also: type(vVar) is str] [WARNING: returns False: "abc" is str] R: ___ [e.g. typeof(vVar) == "character"] Ruby: ___ [e.g. vVar.is_a? String] Rust: ___ [e.g. type_name_of_val(&vVar) == "&str"] [requires: use std::any::type_name_of_val] [also: compare against "alloc::string::String"] Scala: ___ [e.g. vVar.isInstanceOf[String]] SQL (MySQL): ___ SQL (PostgreSQL): ___ [e.g. pg_typeof(MyCol)::text = 'text'] [also: pg_typeof(MyCol) = 'text'::regtype] SQL (SQLite): ___ [e.g. typeof(MyCol) == 'text'] Swift: ___ [e.g. vVar is String] UFL: Any.IsObject [is the value an object (e.g. is object: array/map, e.g. not object: 'primitive'/'value'/int/float/string/bool/null) (definitions of a primitive/value/non-object vary)][e.g. for a custom print function, which 'to string' approach to use] AutoHotkey: vIsObj := IsObject(vVar) C++: ___ [can use: vIsObj = !std::is_fundamental<decltype(vVar)>::value && !std::is_same<decltype(vVar),std::string>::value] [requires: #include <type_traits>] C#: ___ [can use: vIsObj = !vVar.GetType().IsPrimitive && !(vVar is string)] Crystal: ___ [can use: vIsObj = !(vVar.is_a?(Nil) || vVar.is_a?(Bool) || vVar.is_a?(Int) || vVar.is_a?(Float) || vVar.is_a?(Char) || vVar.is_a?(String))] Excel: ___ Excel VBA: vIsObj = IsObject(vVar) Or IsArray(vVar) Go: ___ [can use: reflect.TypeOf] Java: ___ [can use (to check for non-primitive non-string): var vIsObj = !(Integer.class.isInstance(vVar) || Byte.class.isInstance(vVar) || Short.class.isInstance(vVar) || Long.class.isInstance(vVar) || Float.class.isInstance(vVar) || Double.class.isInstance(vVar) || Boolean.class.isInstance(vVar) || Character.class.isInstance(vVar) || ((Object)vVar).getClass().equals(String.class))] JavaScript: vIsObj = (typeof vVar == "object") && (vVar !== null) Kotlin: ___ [can use (to check for non-primitive non-string): vIsObj = (vVar::class.javaPrimitiveType == null) && (vVar !is String)] PHP: $vIsObj = is_object($vVar) || is_array($vVar) Python: ___ [can use: vIsObj = not isinstance(vVar, str|int|float|None)] [note: bool is a subclass of int (i.e. int covers int and bool), e.g. 'isinstance(True, int)' returns True] R: ___ [can use: vIsObj = is.na(match(class(vVar), c("numeric", "integer", "character", "logical", "NULL")))] [note: it may be desirable to exclude vectors of size not equal to 1 by testing length()] Ruby: ___ [can use: vIsObj = !(vVar.is_a?(NilClass) || vVar.is_a?(TrueClass) || vVar.is_a?(FalseClass) || vVar.is_a?(Integer) || vVar.is_a?(Float) || vVar.is_a?(String))] Rust: ___ Scala: ___ [can use: var vIsObj = !(vVar.isInstanceOf[Int] || vVar.isInstanceOf[Byte] || vVar.isInstanceOf[Short] || vVar.isInstanceOf[Long] || vVar.isInstanceOf[Float] || vVar.isInstanceOf[Double] || vVar.isInstanceOf[Boolean] || vVar.isInstanceOf[Char] || vVar.getClass().getSimpleName().equals("String"))] [WARNING: throws on nulls] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: SELECT pg_typeof(MyVar)::text ~ '^json|\[]$'] [algorithm: check if type begins with 'json' or ends with '[]', you may want to check for other types also] SQL (SQLite): ___ Swift: ___ [can use: vIsObj = !((vVar is String) || (vVar is Int) || (vVar is Float) || (vVar is Double) || (vVar is Bool))] UFL: Any.IsArray [e.g. for a custom print function (e.g. use string join on 1-dimensional arrays)] AutoHotkey: vVar is Array C++: std::is_array<decltype(vVar)>::value [requires: #include <type_traits>] C#: vVar is Array Crystal: vVar.is_a?(Array) Excel: ___ Excel VBA: IsArray(vVar) Go: ___ [can use: reflect.TypeOf] Java: ((Object)vVar).getClass().isArray() JavaScript: Array.isArray(vVar) Kotlin: vVar::class.java.isArray PHP: is_array($vVar) [also ('keys consist of consecutive numbers from 0 to count($array)-1'): array_is_list($vVar)] Python: isinstance(vVar, list) R: ___ [can use: vIsVec = is.vector(vVar) & !is.list(vVar)] [WARNING: in R, a 'primitive' and a one-item vector (containing a 'primitive') are identical] [note: length(vVar) to get the vector item count, nchar(vVar) to get a string's length] [WARNING: R uses the word 'primitive' regarding function types] Ruby: vVar.is_a?(Array) Rust: ___ Scala: vVar.getClass().isArray() [WARNING: throws on nulls] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: SELECT pg_typeof(MyVar)::text = 'integer[]'] [also: SELECT right(pg_typeof(MyVar)::text, 2) = '[]'] [e.g. types: 'integer[]', 'text[]', 'numeric[]', 'double precision[]'] SQL (SQLite): ___ Swift: vVar is Array<Any> UFL: (Any.NewDemo) [or AnyNewDemo/VarAnyDemo/VarMultiTypeDemo][demonstrate a variable that can take any type][see also: Array.NewAnyDemo/Array.NewAnyFalsyDemo/VarDeclSet] AutoHotkey: vVar := 123, vVar := "abc", MsgBox(vVar) C++: ___ C#: object vVar = 123; vVar = "abc"; Console.WriteLine(vVar); Crystal: vVar = 123; vVar = "abc"; p vVar Excel: ___ Excel VBA: vVar = 123: vVar = "abc": Debug.Print vVar Go: var vVar any = 123; vVar = "abc"; fmt.Println(vVar) Java: Object vVar = 123; vVar = "abc"; System.out.println(vVar); JavaScript: vVar = 123; vVar = "abc"; console.log(vVar); Kotlin: vVar = 123; vVar = "abc"; println(vVar) PHP: $vVar = 123; $vVar = "abc"; var_export($vVar); Python: vVar = 123; vVar = "abc", print(vVar) R: vVar = 123; vVar = "abc"; print(vVar) Ruby: vVar = 123; vVar = "abc"; p vVar Rust: ___ [can use: let mut vVar: &dyn std::any::Any = &123; vVar = &"abc"; println!("{}", vVar.downcast_ref::<&str>().unwrap());] Scala: var vVar: Any = 123; vVar = "abc"; println(vVar) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var vVar: Any = 123; vVar = "abc"; print(vVar) UFL: Any.CopyRef [create reference][note: object of any type][i.e. multiple variables point to the same object, so 'modifying one modifies all'][see also: Array.Clone/Map.Clone/Object.Clone/Range.Clone/Tuple.Clone/Any.DelRef/Array.EqualsRef] AutoHotkey: oObjNew := oObj [also: ObjAddRef()] C++: &oObjNew = oObj [e.g. MyStruct &oObjNew = oObj] [e.g. int (&oArrayNew)[] = oArray] [e.g. std::string (&oArrayNew)[] = oArray] [e.g. std::map<std::string,std::string> &oMapNew = oMap] [e.g. auto &oRangeNew = oRange] [e.g. auto &oVecNew = oVec] C#: oObjNew = oObj Crystal: oObjNew = oObj [WARNING (struct/record instances): 'oObjNew = oObj' copies (clones) an object] [note: 'Structs inherit from Value'] [also: get object pointer: pObj := &oObj] Excel: ___ Excel VBA: Set oObjNew = oObj [note: this fails with Array objects, there is not a standard way to create a reference to an Array object] Go: oObjNew = oObj [WARNING (struct instances): 'oObjNew = oObj' copies (clones) an object] Java: oObjNew = oObj JavaScript: oObjNew = oObj Kotlin: oObjNew = oObj PHP: $oObjNew = $oObj [WARNING: for arrays, this copies (clones) the array, instead, do: $oArrayNew = &$oArray] Python: oObjNew = oObj R: ___ [WARNING: 'oObjNew = oObj' copies (clones) an object] Ruby: oObjNew = oObj Rust: ___ Scala: oObjNew = oObj SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oObjNew = oObj [WARNING: for value types (e.g. Array/Dictionary/Tuple/Struct/Enum), this copies (clones) the object] UFL: Any.DelRef [or Any.DeleteRef][delete object reference (and delete object if it's the last reference)][note: object of any type][see also: VarDelete] AutoHotkey: oObj := unset [note: in AHK v1: 'oObj := ""' and 'oObj := 0' were common] [also: ObjRelease()] C++: delete oObj [also: delete[] oObj] [note: 'delete'/'delete[]' must be used for variables created with 'new'] [note: 'free' must be used for variables created with 'malloc'] C#: oObj = null Crystal: oObj = nil Excel: ___ Excel VBA: Set oObj = Nothing [note: doesn't work with all types] Go: oObj = nil Java: oObj = null JavaScript: oObj = null [also: oObj = undefined] [also: void operator] Kotlin: oObj = null PHP: unset($oObj) [also: $oObj = null] [note: unset() sets contents to null] Python: del oObj [also: oObj = None] R: oObj = NULL [also: rm(oObj1, oObj2, oObj3)] Ruby: oObj = nil Rust: ___ [can use (if appropriate): drop(oObj)] Scala: oObj = null SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oObj = nil UFL: (Any.Address) [or VarPtr/VarAddress/VarAddr/ObjPtr/ObjAddress/ObjAddr][return an address/pointer to a variable/value/object (or an internal feature)][note: roughly speaking a pointer combines an address/size/type][e.g. check if 2 variables refer to the same object][e.g. pass an address to a function][see also: OpEquals/DateClone] AutoHotkey: vAddr := ObjPtr(oObj) [also: vAddr := ObjPtrAddRef(oObj)] [also: vAddr := StrPtr(vText)] [note: possible variable name: pObj, pText] C++: vAddr = (unsigned long long)&oObj [also: std::addressof(oObj)] C#: ___ [can use (in an 'unsafe' block): vAddr = (ulong)&oObj] Crystal: ___ [can use (may work): vAddr = oObj.object_id << 1] Excel: ___ Excel VBA: [also: vAddr = VarPtr(oObj)] [also: vAddr = ObjPtr(oObj)] [also: vAddr = StrPtr(vText)] Go: vAddr := new(big.Int); vAddr.SetString(fmt.Sprintf("%p", &oObj), 0) [requires: import "math/big"] Java: vAddr = System.identityHashCode(oObj) [also: vAddr = oObj.hashCode()] JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: vAddrHex = paste0("0x", substring(sub(" .*$", "", capture.output(.Internal(inspect(oObj)))), 2)) [WARNING: as.integer(vAddrHex) would truncate it] Ruby: ___ [can use (may work): vAddr = oObj.object_id << 1] Rust: vAddr = &oObj as *const i32 as u64 Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var vAddrHex = ""; withUnsafePointer(to:&oObj) {vAddrHex = String(describing:$0)} [also: var vAddrHex = String(describing:Unmanaged.passUnretained(oObj).toOpaque())] [WARNING: for some objects (e.g. an array/map), if one is cloned, the original/clone may initially point to the same data (this will change if either one is modified): unsafeBitCast(oObj, to: Int.self)]
UFL: Array.Print [print the values][tested on int/float/string arrays][MAJOR WARNING: some languages don't put quotes around strings, making blank/whitespace strings invisible, see Array.PrintQuote for workarounds][see also: Array.Join/Array.ToString/JsonFromObj] AutoHotkey: ___ C++: for (const auto& vValue : oArray) std::cout << vValue << "," [also (for array on the heap): for (const auto& vValue : std::views::counted(oArray, vSize)) std::cout << vValue << ","] [requires (views::counted): #include <ranges>] [also (for array on the heap): for (const auto& vValue : *(int(*)[vSize])oArray)] [also (for array on the heap): for (const auto& vValue : *(int(*)[vSize])&oArray[0])] C#: Console.WriteLine("[" + String.Join(",", oArray) + "]") [note: also works with lists] Crystal: p oArray [note: prints on 1 line, and appends a linefeed] [also: puts oArray.inspect] Excel: ___ Excel VBA: Debug.Print "[" & Join(oArray, ",") & "]" Go: fmt.Println(oArray) [requires: import "fmt"] Java: System.out.println(java.util.Arrays.toString(oArray)) [also: System.out.println(java.util.Arrays.deepToString(oArray))] [note: deepToString() worked on: String[]/int[][]/double[][]/String[][], failed on: int[]/double[]] [also: System.out.println(oList)] JavaScript: console.log(oArray) Kotlin: println(oArray.toList()) [also: println(oArray.contentToString())] PHP: var_export($oArray) [also: var_dump($oArray)] [also: print_r($oArray)] [note: var_export/var_dump/print_r all print keys and values] Python: print(oList) [also: print("\n".join(oList))] [also: print("\n".join(map(str, oList)))] R: print(oVec) Ruby: p oArray [note: prints on 1 line, and appends a linefeed] [also: puts oArray.inspect] Rust: println!("{:?}", oArray) Scala: println(oArray.mkString(", ")) [also: println(oArray.toList)] SQL (MySQL): SELECT v FROM MyTable SQL (PostgreSQL): SELECT v FROM MyTable SQL (SQLite): SELECT v FROM MyTable Swift: print(oArray) UFL: Array.PrintQuote [string arrays, print the values, with (double/single/backtick) quotes around items, to make blank/whitespace strings visible][see also: Array.Join/Array.ToString/JsonFromObj/PrintQuote] AutoHotkey: ___ C++: std::cout << "["; for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) std::cout << (i?",":"") << "\"" << oArray[i] << "\""; std::cout << "]\n"; C#: Console.WriteLine(JsonSerializer.Serialize(oArray)) [also: Console.WriteLine("[" + String.Join(", ", oArray.Select(v=>'"'+v+'"')) + "]")] [also (no includes needed): Console.WriteLine(oArray.Length==0 ? "[]" : "[\"" + String.Join("\", \"", oArray) + "\"]")] [requires (JsonSerializer): using System.Text.Json] [requires (Select): using System.Linq] Crystal: p oArray [also: puts oArray.to_json] [requires (to_json): require "json"] Excel: ___ Excel VBA: Debug.Print IIf(UBound(oArray) < LBound(oArray), "[]", "[""" & Join(oArray, """, """) & """]") Go: fmt.Printf("%q\n", oArray) [note: %q: no commas between items] [also: oBuf, _ := json.Marshal(oArray); fmt.Println(string(oBuf))] [requires (json): import "encoding/json"] Java: System.out.println(oArray.length==0 ? "[]" : "[\"" + String.join("\", \"", oArray) + "\"]") JavaScript: console.log(oArray) [also: console.log(JSON.stringify(oArray))] [note: console.log(oArray) uses oArray.toString() which uses single quotes, else double quotes/backticks depending on the contents] Kotlin: println("[" + oArray.map{'"'+it+'"'}.joinToString() + "]") [also: println(if (oArray.count()==0) "[]" else "[\"" + oArray.joinToString("\", \"") + "\"]")] PHP: echo json_encode($oArray) . "\n" Python: print(oList) [also: print(json.dumps(oList))] [also: print("["+", ".join(map(lambda v:'"'+v+'"', oList))+"]")] [requires (json): import json] R: cat(paste0("[", ifelse(!length(oVec), "", paste(paste0('"', oVec, '"'), collapse=", ")), "]\n", sep="")) Ruby: p oArray [also: puts oArray.to_json] [requires (to_json): require "json"] Rust: println!("{:?}", oArray) Scala: println("[" + oArray.map("\""+_+"\"").mkString(", ") + "]") [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ [also: SELECT '"'||v||'"' FROM unnest(MyArray) v] SQL (SQLite): ___ Swift: print(oArray) [also: print(String(data:try! JSONEncoder().encode(oArray), encoding:.utf8)!)] [requires (JSONEncoder): import Foundation] UFL: Array.PrintWithIndex [or Array.PrintKeyValue][print the key-value pairs][tested on int/float/string arrays][see also: Array.LoopWithIndex/Array.Entries/Array.ToMap/Map.Print/PrintKeyValueAsPair] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) std::cout << i << ":" << oArray[i] << "\n" [also: for (int i=0; i<oVec.size(); i++) std::cout << i << ":" << oVec[i] << "\n"] C#: Console.WriteLine(String.Join("\n", oArray.Select((v,k)=>$"{k}:{v}"))) [also: Console.WriteLine(String.Join("\n", oArray.Select((v,k)=>String.Join(":",k,v))))] [also: Console.WriteLine(String.Join("\n", oArray.Select((v,k)=>new{k,v})))] [also: Console.WriteLine(String.Join("\n", oArray.Select((v,k)=>new{MyKey=k,MyValue=v})))] [requires (Select): using System.Linq] Crystal: p Hash.zip((0...oArray.size).to_a, oArray) Excel: ___ Excel VBA: For i = LBound(oArray) To UBound(oArray): Debug.Print i & ":" & oArray(i): Next [note: using ':' to write multiple code lines on one line] Go: for k, v := range oArray { fmt.Printf("%v: %v\n", k, v) } [note: the Go Playground will auto-format this] Java: for (int i=0; i<oArray.length; i++) System.out.println(i + ":" + oArray[i]) JavaScript: console.log([...oArray.entries()].join("\n")) Kotlin: println(oArray.mapIndexed{k,v->k to v!!}.toMap()) [also: println(oArray.mapIndexed{k,v->k to v!!})] [also: println(oArray.mapIndexed{k,v->k to v!!}.joinToString("\n"))] [also: println(oArray.withIndex().toList())] PHP: var_export($oArray) [also: var_dump($oArray)] [also: print_r($oArray)] Python: print({k:v for k,v in enumerate(oList)}) [also: print(list(enumerate(oList)))] [also: print("\n".join(map(str, enumerate(oList))))] [also: print("\n".join(map(lambda v : str(v[0])+":"+str(v[1]), enumerate(oList))))] [also: print("\n".join([str(k)+":"+str(v) for k,v in enumerate(oList)]))] R: for (i in 1:length(oVec)) {print(paste(i, oVec[i], sep=": "))} Ruby: p oArray.map.with_index{|v,k| [k,v]}.to_h [also: p ((0...oArray.length).zip oArray).to_h] [also: p Hash[(0...oArray.length).zip oArray]] Rust: println!("{:?}", oArray.iter().enumerate().collect::<Vec<_>>()) [also: println!("{}", oArray.iter().enumerate().map(|(k,v)| format!("{}:{}", k, v)).collect::<Vec<_>>().join("\n"))] Scala: println(oArray.zipWithIndex.mkString(", ")) [also: println(oArray.zipWithIndex.toList)] [also: for ((v,k) <- oArray.view.zipWithIndex) println((k,v))] SQL (MySQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] SQL (PostgreSQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] [also: SELECT k,v FROM unnest(MyArray) WITH ORDINALITY AS t(v, k)] SQL (SQLite): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] Swift: print(oArray.enumerated().map{($0,$1)}) [also: print(oArray.enumerated().map{String($0)+":"+String($1)}.joined(separator:"\n"))] UFL: Array.LoopValue [loop through the items of an array, get values one-by-one] AutoHotkey: for _, vValue in oArray [also (AHK v2 onwards): for vValue in oArray] C++: for (const auto& vValue : oArray) [also: for (const auto& vValue : oVec)] C#: foreach (var vValue in oArray) Crystal: oArray.each do |vValue| [afterwards: end] Excel: ___ Excel VBA: ___ [can use: For i = LBound(oArray) To UBound(oArray)] [note: vValue = oArray(i)] [also (for collections): For Each vValue In oColl] [afterwards (both): Next] Go: for _, vValue := range oArray Java: for (var vValue : oArray) JavaScript: for (const vValue of oArray) [also (ES6): oArray.forEach(function (vValue) {...})] [also: for (var i=0; i<oArray.length; i++)] [MAJOR WARNING: 'of'/'in': 'vValue of oArray' versus 'vKey in oArray' (WARNING: 'in': returns vKey as string type)] Kotlin: for (vValue in oArray) PHP: foreach ($oArray as $vValue) Python: for vValue in oList: R: for (vValue in oVec) [also: for (vValue in oList)] Ruby: for vValue in oArray [afterwards: end] Rust: for vValue in oArray Scala: for (vValue <- oArray) [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for vValue in oArray UFL: Array.LoopWithIndex [or Array.LoopKeyValue][loop through the items of an array, get key-value pairs one-by-one] AutoHotkey: for vKey, vValue in oArray C++: ___ [can use: for (const auto& vValue : oArray)] [note (won't work on all object types): vKey = &vValue-&oArray[0]] [also: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++)] [also: for (int i=0; i<oVec.size(); i++)] C#: foreach (var e in oArray.Select((v,k)=>new{k,v})) [also: foreach (var oEntry in oArray.Select((v,k)=>new{MyKey=k,MyValue=v}))] [e.g. e.k, e.v] [e.g. oEntry.MyKey, oEntry.MyValue] [requires (Select): using System.Linq] Crystal: oArray.each_with_index do |vValue,vKey| [WARNING: order is value then key] [afterwards: end] Excel: ___ Excel VBA: ___ [can use: For i = LBound(oArray) To UBound(oArray)] [note: vValue = oArray(i)] [afterwards: Next] Go: for vKey, vValue := range oArray Java: ___ [can use: for (int i=0; i<oArray.length; i++)] [note: vValue = oArray[i]] JavaScript: for (const [vKey, vValue] of oArray.entries()) [also (ES6): oArray.forEach(function (vValue, vKey) {...})] [also (unspecified order): for (var vKey in oArray)] Kotlin: for ((vKey, vValue) in oArray.withIndex()) PHP: foreach ($oArray as $vKey=>$vValue) Python: for vKey, vValue in enumerate(oList): R: for (i in 1:length(oVec)) [note: vValue = oVec[i]] [also: for (i in seq_along(oVec))] Ruby: for vValue, vKey in oArray.each_with_index [WARNING: order is value then key] [afterwards: end] Rust: for (vKey, vValue) in oArray.iter().enumerate() Scala: for ((vValue,vKey) <- oArray.view.zipWithIndex) [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for (vKey, vValue) in oArray.enumerated() UFL: Array.ForEach [or Array.LoopForEach][call a function once for each item of an array][see also: Array.Map/Array.LoopValue/ForEachPrintDemo] AutoHotkey: ___ C++: std::for_each(std::begin(oArray), std::end(oArray), oFunc) [note: Func receives value] [requires (for_each): #include <algorithm>] C#: ___ [can use: foreach (var v in oArray) oFunc(v)] Crystal: oArray.each{|v| oFunc.call(v)} [also: oArray.each(&oFunc)] Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.stream(oArray).forEach(oFunc) [note: Func receives value] [requires (Arrays): import java.util.*] JavaScript: oArray.forEach(oFunc) [also: oArray.forEach(v=>oFunc(v))] [note: Func receives value/key/object] Kotlin: oArray.forEach(oFunc) [also: oArray.forEach{oFunc(it)}] [note: Func receives value] PHP: array_walk($oArray, $oFunc) [also: array_walk($oArray, fn($v)=>$oFunc($v))] [also: foreach ($oArray as $v) $oFunc($v)] Python: ___ [can use: for v in oList: oFunc(v)] R: ___ [can use: for (v in oVec) oFunc(v)] Ruby: oArray.each{|v| oFunc.call(v)} [also: oArray.each(&oFunc)] Rust: oArray.iter().for_each(|v| oFunc(v)) Scala: oArray.foreach(oFunc) [also: oArray.foreach(oFunc(_))] [also: oArray.foreach(v=>oFunc(v))] [note: Func receives value] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray.forEach(oFunc) [also: oArray.forEach{oFunc($0)}] [note: Func receives value] UFL: Array.ForEachWithIndex [or Array.LoopForEachWithIndex][call a function once for each item of an array][see also: Array.Map/Array.Entries/Array.LoopWithIndex] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oFunc(i, oArray[i])] [also: for (int i=0; i<oVec.size(); i++) oFunc(i, oVec[i])] C#: ___ [can use: foreach (var e in oArray.Select((v,k)=>new{k,v})) oFunc(e.k,e.v)] [requires (Select): using System.Linq] Crystal: oArray.each_with_index{|v,k| oFunc.call(k,v)} Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: IntStream.range(0, oArray.length).forEach(i->oFunc.accept(i,oArray[i]))] [requires: import java.util.stream.*] JavaScript: oArray.forEach(oFunc) [also: oArray.forEach((v,k)=>oFunc(k,v))] [note: Func receives value/key/object] [also: oArray.entries().forEach(v=>oFunc(v[0],v[1]))] Kotlin: oArray.forEachIndexed(oFunc) [also: oArray.forEachIndexed{k,v->oFunc(k,v)}] [note: Func receives key/value] PHP: array_walk($oArray, $oFunc) [also: array_walk($oArray, fn($v,$k)=>$oFunc($k,$v))] [also: foreach ($oArray as $k=>$v) $oFunc($k,$v)] Python: ___ [can use: for k,v in enumerate(oList): oFunc(k,v)] R: ___ [can use: for (k in 1:length(oVec)) oFunc(k,oVec[k])] Ruby: oArray.each_with_index{|v,k| oFunc.call(k,v)} Rust: oArray.iter().enumerate().for_each(|(k,v)| oFunc(k,*v)) Scala: oArray.view.zipWithIndex.foreach((v,k)=>oFunc(k,v)) [note: Func receives value/key] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray.enumerated().forEach(oFunc) [also: oArray.enumerated().forEach{oFunc($0,$1)}] [note: Func receives key/value] UFL: Array.NewEmptyIntDemo [or Array.NewIntEmptyDemo/Array.EmptyNewIntDemo/Array.NewBasicDemo][create an empty array] AutoHotkey: oArray := [] [type: Array] [note: 1-based] C++: int oArray[] = {} [type: int[0] (typeid: A0_i)] [also: std::vector<int> oVec] [type (vector): std::vector<int> (typeid: NSt3__26vectorIiNS_9allocatorIiEEEE)] C#: int[] oArray = {} [type: Int32[]] [also (C# 12 onwards): int[] oArray = []] [also: var oList = new List<int>()] [requires (List): using System.Collections.Generic] Crystal: oArray = [] of Int32 [type: Array(Int32)] Excel: ___ Excel VBA: oArray = Array() [type: Variant()] [note: 0-based by default, can specify the start index] [note: an alternative class: Set oArray = CreateObject("System.Collections.ArrayList")] Go: oArray := [0]int{} [type: [0]int] [note: to omit the count (to let the compiler count the members), use '...', e.g. oArray := [...]int{}] [WARNING: omitting the count, i.e. '[]', creates a slice, not an array] Java: int[] oArray = {} [type: int[]] [also: var oList = new ArrayList<Integer>()] [requires (ArrayList): import java.util.*] JavaScript: oArray = [] [type: Array] Kotlin: oArray = arrayOf<Int>() [type: Array] [also: oArray: Array<Int> = arrayOf()] PHP: $oArray = [] [type: array] [also: $oArray = array()] [note: an associative array that also has linear array functionality] [note: 0-based by default, can specify the start index] Python: oList = [] [type: list] R: oVec = numeric(0) [type (64-bit float, commonly used for ints/floats): double (class: numeric)] [also (32-bit int): oVec = integer(0)] [type (integer): integer] [note: 1-based] [WARNING: c() returns a NULL] [also (1-item vec to 0-item vec): oVec = c(0)[-1]] [note: oVec[-n] copies everything except element n] [WARNING: for vectors, typeof()/class() report the type of the item] Ruby: oArray = [] [type: Array] Rust: oArray: [i32; 0] = [] [type: '[i32; 0]'] [also: let mut oVec: Vec<i32> = vec![]] Scala: oArray = Array[Int]() [type: int[]] [also: var oList = List[Int]()] [type (empty list): Nil$] [type (non-empty list): $colon$colon] SQL (MySQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER) [type: (table)] [note: 1-based] [note (INTEGER PRIMARY KEY AUTO_INCREMENT): when adding keys, if k is omitted, an integer value for k is auto-generated] SQL (PostgreSQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER) [type: (table)] [note: 1-based] [note (SERIAL PRIMARY KEY): when adding keys, if k is omitted, an integer value for k is auto-generated] [note: ARRAY[] returns 1-based arrays] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER) STRICT [type: (table)] [note: 1-based] [note (INTEGER PRIMARY KEY): when adding keys, if k is omitted, an integer value for k is auto-generated, add 'AUTOINCREMENT' for slightly different rules] Swift: oArray = [Int]() [type: Array<Int>] UFL: (Array.NewEmptyFloatDemo) [or Array.NewFloatEmptyDemo/Array.EmptyNewFloatDemo][create an empty array] AutoHotkey: oArray := [] [type: Array] [note: 1-based] C++: double oArray[] = {} [type: double[0] (typeid: A0_d)] [also: std::vector<double> oVec] [type (vector): std::vector<double> (typeid: NSt3__26vectorIdNS_9allocatorIdEEEE)] C#: double[] oArray = {} [type: Double[]] [also (C# 12 onwards): double[] oArray = []] [also: var oList = new List<double>()] [requires (List): using System.Collections.Generic] Crystal: oArray = [] of Float64 [type: Array(Float64)] Excel: ___ Excel VBA: oArray = Array() [type: Variant()] [note: 0-based by default, can specify the start index] [note: an alternative class: Set oArray = CreateObject("System.Collections.ArrayList")] Go: oArray := [0]float64{} [type: [0]float64] [note: to omit the count (to let the compiler count the members), use '...', e.g. oArray := [...]double{}] [WARNING: omitting the count, i.e. '[]', creates a slice, not an array] Java: double[] oArray = {} [type: double[]] [also: var oList = new ArrayList<Double>()] [requires (ArrayList): import java.util.*] JavaScript: oArray = [] [type: Array] Kotlin: oArray = arrayOf<Double>() [type: Array] [also: oArray: Array<Double> = arrayOf()] PHP: $oArray = [] [type: array] [also: $oArray = array()] [note: an associative array that also has linear array functionality] [note: 0-based by default, can specify the start index] Python: oList = [] [type: list] R: oVec = numeric(0) [type: double (class: numeric)] [note: 1-based] [WARNING: c() returns a NULL] [also (1-item vec to 0-item vec): oVec = c(0)[-1]] [note: oVec[-n] copies everything except element n] [WARNING: for vectors, typeof()/class() report the type of the item] Ruby: oArray = [] [type: Array] Rust: oArray: [f64; 0] = [] [type: '[f64; 0]'] [also: let mut oVec: Vec<f64> = vec![]] Scala: oArray = Array[Double]() [type: double[]] [also: var oList = List[Double]()] [type (empty list): Nil$] [type (non-empty list): $colon$colon] SQL (MySQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v DOUBLE) [type: (table)] [note: 1-based] [note: see 'Array.NewEmptyIntDemo' for info about auto-increment] SQL (PostgreSQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v FLOAT) [type: (table)] [note: 1-based] [note: see 'Array.NewEmptyIntDemo' for info about auto-increment] [note: ARRAY[] returns 1-based arrays] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v REAL) STRICT [type: (table)] [note: 1-based] [note: see 'Array.NewEmptyIntDemo' for info about auto-increment] Swift: oArray = [Double]() [type: Array<Double>] UFL: Array.NewEmptyStrDemo [or Array.NewStrEmptyDemo/Array.EmptyNewStrDemo/Array.NewEmptyStringDemo/Array.NewStringEmptyDemo/Array.EmptyNewStringDemo][create an empty array] AutoHotkey: oArray := [] [type: Array] [note: 1-based] C++: std::string oArray[] = {} [type: std::string[0] (typeid: A0_NSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE)] [also: std::vector<std::string> oVec] [type (vector): std::vector<std::string> (typeid: NSt3__26vectorINS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEENS4_IS6_EEEE)] C#: string[] oArray = {} [type: String[]] [also (C# 12 onwards): string[] oArray = []] [also: var oList = new List<string>()] [requires (List): using System.Collections.Generic] Crystal: oArray = [] of String [type: Array(String)] Excel: ___ Excel VBA: oArray = Array() [type: Variant()] [note: 0-based by default, can specify the start index] [note: an alternative class: Set oArray = CreateObject("System.Collections.ArrayList")] Go: oArray := [0]string{} [type: [0]string] [note: to omit the count (to let the compiler count the members), use '...', e.g. oArray := [...]string{}] [WARNING: omitting the count, i.e. '[]', creates a slice, not an array] Java: String[] oArray = {} [type: String[]] [also: var oList = new ArrayList<String>()] [requires (ArrayList): import java.util.*] JavaScript: oArray = [] [type: Array] Kotlin: oArray = arrayOf<String>() [type: Array] [also: oArray: Array<String> = arrayOf()] PHP: $oArray = [] [type: array] [also: $oArray = array()] [note: an associative array that also has linear array functionality] [note: 0-based by default, can specify the start index] Python: oList = [] [type: list] R: oVec = character(0) [type: character] [note: 1-based] [WARNING: c() returns a NULL] [also (1-item vec to 0-item vec): oVec = c(0)[-1]] [note: oVec[-n] copies everything except element n] [WARNING: for vectors, typeof()/class() report the type of the item] Ruby: oArray = [] [type: Array] Rust: oArray: [&str; 0] = [] [type: '[&str; 0]'] [also: oArray: [String; 0] = []] [type (String): '[alloc::string::String; 0]'] [also: let mut oVec: Vec<&str> = vec![]] Scala: oArray = Array[String]() [type: String[]] [also: var oList = List[String]()] [type (empty list): Nil$] [type (non-empty list): $colon$colon] SQL (MySQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v TEXT) [type: (table)] [note: 1-based] [note: see 'Array.NewEmptyIntDemo' for info about auto-increment] SQL (PostgreSQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v TEXT) [type: (table)] [note: 1-based] [note: see 'Array.NewEmptyIntDemo' for info about auto-increment] [note: ARRAY[] returns 1-based arrays] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v TEXT) STRICT [type: (table)] [note: 1-based] [note: see 'Array.NewEmptyIntDemo' for info about auto-increment] Swift: oArray = [String]() [type: Array<String>] UFL: Array.NewIntDemo [create an array containing 1, 2, 3] AutoHotkey: oArray := [1, 2, 3] C++: int oArray[] = {1, 2, 3} [also: std::vector<int> oVec = {1, 2, 3}] C#: int[] oArray = {1, 2, 3} [also: var oList = new List<int>{1, 2, 3}] [requires (List): using System.Collections.Generic] Crystal: oArray = [1, 2, 3] Excel: ___ Excel VBA: oArray = Array(1, 2, 3) Go: oArray := [...]int{1, 2, 3} [also: oSlice := []int{1, 2, 3}] [also: oArray := [3]int{1, 2, 3}] Java: int[] oArray = {1, 2, 3} [also (fixed size): List<Integer> oList = Arrays.asList(1, 2, 3)] [also (read-only): var oList = List.of(1, 2, 3)] [note: see 'Array.ToList' to create a mutable list from an array] JavaScript: oArray = [1, 2, 3] Kotlin: oArray = arrayOf(1, 2, 3) PHP: $oArray = [1, 2, 3] Python: oList = [1, 2, 3] R: oVec = c(1, 2, 3) [note: 64-bit floats] [also (32-bit ints): as.integer(c(1, 2, 3))] [WARNING: these are equivalent: oVec = 1; oVec = c(1)] [WARNING: these are equivalent: oVecNew = as.character(oVec); oVecNew = mapply(\(v) as.character(v), oVec)] Ruby: oArray = [1, 2, 3] Rust: oArray = [1, 2, 3] Scala: oArray = Array(1, 2, 3) [also: var oList = List(1, 2, 3)] SQL (MySQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v INTEGER); INSERT INTO MyTable (v) VALUES (1), (2), (3); SQL (PostgreSQL): CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v INTEGER); INSERT INTO MyTable (v) VALUES (1), (2), (3); [also: ARRAY[1, 2, 3]] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER) STRICT; INSERT INTO MyTable (v) VALUES (1), (2), (3); Swift: oArray = [1, 2, 3] [e.g. empty array: oArray = [Int]()] UFL: Array.OverwriteIntDemo [or Array.NewOverwriteIntDemo][overwrite an existing array (redefine/reassign)][note: the syntax is often identical to creating an array][replace an array with a new array][this syntax can often be used to temporarily create an array, e.g. to print/look up/test values][see also: Array.Clear] AutoHotkey: oArray := [1, 2, 3] C++: ___ [can use: oVec = {1, 2, 3}] [also: oVec = std::vector<int>{1, 2, 3}] C#: oArray = [1, 2, 3] [also: oArray = (int[])[1, 2, 3]] [also: oArray = new int[]{1, 2, 3}] [also: oList = [1, 2, 3]] [also: oList = (List<int>)[1, 2, 3]] [also: oList = new List<int>{1, 2, 3}] Crystal: oArray = [1, 2, 3] Excel: ___ Excel VBA: oArray = Array(1, 2, 3) Go: oArray = [...]int{1, 2, 3} [also: oSlice = []int{1, 2, 3}] [note: can only overwrite an existing array with an array of the same size] Java: oArray = new int[]{1, 2, 3} [also: oList = Arrays.asList(1, 2, 3)] [also: oList = List.of(1, 2, 3)] JavaScript: oArray = [1, 2, 3] Kotlin: oArray = arrayOf(1, 2, 3) PHP: $oArray = [1, 2, 3] Python: oList = [1, 2, 3] R: oVec = c(1, 2, 3) Ruby: oArray = [1, 2, 3] Rust: oArray = [1, 2, 3] [note: can only overwrite an existing array with an array of the same size (unless use 'let')] Scala: oArray = Array(1, 2, 3) [also: oList = List(1, 2, 3)] [FIXME] SQL (MySQL): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES (1), (2), (3);] [note: clears the table, then adds rows] [FIXME] SQL (PostgreSQL): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES (1), (2), (3);] [note: clears the table, then adds rows] SQL (SQLite): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES (1), (2), (3);] [note: clears the table, then adds rows] Swift: oArray = [1, 2, 3] UFL: (Array.NewFloatDemo) [or Array.NewDoubleDemo][create an array containing 1.1, 2.2, 3.3] AutoHotkey: oArray := [1.1, 2.2, 3.3] C++: double oArray[] = {1.1, 2.2, 3.3} [also: std::vector<double> oVec = {1.1, 2.2, 3.3}] C#: double[] oArray = {1.1, 2.2, 3.3} [also: var oList = new List<double>{1.1, 2.2, 3.3}] [note: 'double' is preferred, 'Double' also works] [requires (List): using System.Collections.Generic] Crystal: oArray = [1.1, 2.2, 3.3] Excel: ___ Excel VBA: oArray = Array(1.1, 2.2, 3.3) Go: oArray := [...]float64{1.1, 2.2, 3.3} [also: oSlice := []float64{1.1, 2.2, 3.3}] [also: oArray := [3]float64{1.1, 2.2, 3.3}] Java: double[] oArray = {1.1, 2.2, 3.3} [also (fixed size): List<Double> oList = Arrays.asList(1.1, 2.2, 3.3)] [also (read-only): var oList = List.of(1.1, 2.2, 3.3)] [note: see 'Array.ToList' to create a mutable list from an array] JavaScript: oArray = [1.1, 2.2, 3.3] Kotlin: oArray = arrayOf(1.1, 2.2, 3.3) PHP: $oArray = [1.1, 2.2, 3.3] Python: oList = [1.1, 2.2, 3.3] R: oVec = c(1.1, 2.2, 3.3) Ruby: oArray = [1.1, 2.2, 3.3] Rust: oArray = [1.1, 2.2, 3.3] Scala: oArray = Array(1.1, 2.2, 3.3) [also: var oList = List(1.1, 2.2, 3.3)] SQL (MySQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v DOUBLE); INSERT INTO MyTable (v) VALUES (1.1), (2.2), (3.3); SQL (PostgreSQL): CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v FLOAT); INSERT INTO MyTable (v) VALUES (1.1), (2.2), (3.3); [also: '{1.1, 2.2, 3.3}'::float[]] [also (only need to cast the first value/-0.0 as a float): ARRAY['1.1'::float, 2.2, 3.3]] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v REAL) STRICT; INSERT INTO MyTable (v) VALUES (1.1), (2.2), (3.3); Swift: oArray = [1.1, 2.2, 3.3] [e.g. empty array: oArray = [Double]()] UFL: Array.OverwriteFloatDemo [or Array.NewOverwriteFloatDemo][overwrite an existing array (redefine/reassign)][note: the syntax is often identical to creating an array][replace an array with a new array][this syntax can often be used to temporarily create an array, e.g. to print/look up/test values][see also: Array.Clear] AutoHotkey: oArray := [1.1, 2.2, 3.3] C++: ___ [can use: oVec = {1.1, 2.2, 3.3}] [also: oVec = std::vector<double>{1.1, 2.2, 3.3}] C#: oArray = [1.1, 2.2, 3.3] [also: oArray = (double[])[1.1, 2.2, 3.3]] [also: oArray = new double[]{1.1, 2.2, 3.3}] [also: oList = [1.1, 2.2, 3.3]] [also: oList = (List<double>)[1.1, 2.2, 3.3]] [also: oList = new List<double>{1.1, 2.2, 3.3}] Crystal: oArray = [1.1, 2.2, 3.3] Excel: ___ Excel VBA: oArray = Array(1.1, 2.2, 3.3) Go: oArray = [...]float64{1.1, 2.2, 3.3} [also: oSlice = []float64{1.1, 2.2, 3.3}] [note: can only overwrite an existing array with an array of the same size] Java: oArray = new double[]{1.1, 2.2, 3.3} [also: oList = Arrays.asList(1.1, 2.2, 3.3)] [also: oList = List.of(1.1, 2.2, 3.3)] JavaScript: oArray = [1.1, 2.2, 3.3] Kotlin: oArray = arrayOf(1.1, 2.2, 3.3) PHP: $oArray = [1.1, 2.2, 3.3] Python: oList = [1.1, 2.2, 3.3] R: oVec = c(1.1, 2.2, 3.3) Ruby: oArray = [1.1, 2.2, 3.3] Rust: oArray = [1.1, 2.2, 3.3] [note: can only overwrite an existing array with an array of the same size (unless use 'let')] Scala: oArray = Array(1.1, 2.2, 3.3) [also: oList = List(1.1, 2.2, 3.3)] [FIXME] SQL (MySQL): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES (1.1), (2.2), (3.3);] [note: clears the table, then adds rows] [FIXME] SQL (PostgreSQL): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES (1.1), (2.2), (3.3);] [note: clears the table, then adds rows] SQL (SQLite): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES (1.1), (2.2), (3.3);] [note: clears the table, then adds rows] Swift: oArray = [1.1, 2.2, 3.3] UFL: (Array.NewFloatExDemo) [or Array.NewDoubleExDemo][create an array containing floats e.g. -Inf/Inf/NaN][note: -0.0: negative zero][see also: NaN/Infinity] AutoHotkey: oArray := [-123.456, -0.0, 0.0, 123.456, -Abs(Ln(0)), Abs(Ln(0)), Abs(Ln(0)/Ln(0))] C++: double oArray[] = {-123.456, -0.0, 0.0, 123.456, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::quiet_NaN()} C#: double[] oArray = {-123.456, -0.0, 0.0, 123.456, Double.NegativeInfinity, Double.PositiveInfinity, Double.NaN} Crystal: oArray = [-123.456, -0.0, 0.0, 123.456, -Float64::INFINITY, Float64::INFINITY, Float64::NAN] Excel: ___ Excel VBA: oArray = Array(-123.456, -0#, 0#, 123.456, vNInf, vInf, vNaN) [note: need to define NInf/Inf/NaN elsewhere] Go: oArray := [...]float64{-123.456, -math.Abs(0.0), 0.0, 123.456, math.Inf(-1), math.Inf(1), math.NaN()} Java: double[] oArray = {-123.456, -0.0, 0.0, 123.456, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN} JavaScript: oArray = [-123.456, -0.0, 0.0, 123.456, -Infinity, Infinity, NaN] Kotlin: oArray = arrayOf(-123.456, -0.0, 0.0, 123.456, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN) PHP: $oArray = [-123.456, -0.0, 0.0, 123.456, -INF, INF, NAN] Python: oList = [-123.456, -0.0, 0.0, 123.456, float("-inf"), float("inf"), float("nan")] R: oVec = c(-123.456, -0.0, 0.0, 123.456, -Inf, Inf, NaN) Ruby: oArray = [-123.456, -0.0, 0.0, 123.456, -Float::INFINITY, Float::INFINITY, Float::NAN] Rust: oArray = [-123.456, -0.0, 0.0, 123.456, -std::f64::INFINITY, std::f64::INFINITY, std::f64::NAN] Scala: oArray = Array(-123.456, -0.0, 0.0, 123.456, Double.NegativeInfinity, Double.PositiveInfinity, Double.NaN) SQL (MySQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v DOUBLE); INSERT INTO MyTable (v) VALUES (-123.456), (CAST('-0.0' AS DOUBLE)), (0.0), (123.456), (-1.7976931348623157E+308), (1.7976931348623157E+308), (NULL); [WARNING: MySQL often returns NULL where NaN is expected] [note: MySQL doesn't support Infinity, 1.7976931348623157E+308 is approximately equal to the largest non-infinity double] SQL (PostgreSQL): CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v FLOAT); INSERT INTO MyTable (v) VALUES (-123.456), ('-0.0'::float), (0.0), (123.456), ('-Infinity'::float), ('Infinity'::float), ('NaN'::float); [also: '{-123.456, -0.0, 0.0, 123.456, -Infinity, Infinity, NaN}'::float[]] [also (only need to cast the first value/-0.0 as a float): ARRAY['-123.456'::float, '-0.0'::float, '0.0'::float, '123.456'::float, '-Infinity'::float, 'Infinity'::float, 'NaN'::float]] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v REAL) STRICT; INSERT INTO MyTable (v) VALUES (-123.456), (-0.0), (0.0), (123.456), (-1e999), (1e999), (NULL); [WARNING: SQLite often returns NULL where NaN is expected] [MAJOR WARNING: attempts to store -0.0 in a table, store 0.0 (or 0)] Swift: oArray = [-123.456, -0.0, 0.0, 123.456, -Double.infinity, Double.infinity, Double.nan] UFL: Array.NewStrDemo [or Array.NewStringDemo][create an array containing a, b, c] AutoHotkey: oArray := ["a", "b", "c"] C++: std::string oArray[] = {"a", "b", "c"} [also: std::vector<std::string> oVec = {"a", "b", "c"}] C#: string[] oArray = {"a", "b", "c"} [note: 'String[]' also works] [also: var oList = new List<string>{"a", "b", "c"}] [requires (List): using System.Collections.Generic] Crystal: oArray = ["a", "b", "c"] Excel: ___ Excel VBA: oArray = Array("a", "b", "c") Go: oArray := [...]string{"a", "b", "c"} [also: oSlice := []string{"a", "b", "c"}] [also: oArray := [3]string{"a", "b", "c"}] Java: String[] oArray = {"a", "b", "c"} [note: 'string[]' doesn't work] [also (fixed size): List<String> oList = Arrays.asList("a", "b", "c")] [also (read-only): var oList = List.of("a", "b", "c")] [note: see 'Array.ToList' to create a mutable list from an array] JavaScript: oArray = ["a", "b", "c"] Kotlin: oArray = arrayOf("a", "b", "c") PHP: $oArray = ["a", "b", "c"] Python: oList = ["a", "b", "c"] [WARNING: list(): a string becomes 1 element per char, e.g. oList = list("abc")] R: oVec = c("a", "b", "c") Ruby: oArray = ["a", "b", "c"] Rust: oArray = ["a", "b", "c"] Scala: oArray = Array("a", "b", "c") [also: var oList = List("a", "b", "c")] SQL (MySQL): CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v TEXT); INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c'); SQL (PostgreSQL): CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v TEXT); INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c'); [also: ARRAY['a', 'b', 'c']] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v TEXT) STRICT; INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c'); Swift: oArray = ["a", "b", "c"] [e.g. empty array: oArray = [String]()] UFL: Array.OverwriteStrDemo [or Array.NewOverwriteStrDemo][overwrite an existing array (redefine/reassign)][note: the syntax is often identical to creating an array][replace an array with a new array][this syntax can often be used to temporarily create an array, e.g. to print/look up/test values][see also: Array.Clear] AutoHotkey: oArray := ["a", "b", "c"] C++: ___ [can use: oVec = {"a", "b", "c"}] [also: oVec = std::vector<std::string>{"a", "b", "c"}] C#: oArray = ["a", "b", "c"] [also: oArray = (string[])["a", "b", "c"]] [also: oArray = new string[]{"a", "b", "c"}] [also: oList = ["a", "b", "c"]] [also: oList = (List<string>)["a", "b", "c"]] [also: oList = new List<string>{"a", "b", "c"}] Crystal: oArray = ["a", "b", "c"] Excel: ___ Excel VBA: oArray = Array("a", "b", "c") Go: oArray = [...]string{"a", "b", "c"} [also: oSlice = []string{"a", "b", "c"}] [note: can only overwrite an existing array with an array of the same size] Java: oArray = new String[]{"a", "b", "c"} [also: oList = Arrays.asList("a", "b", "c")] [also: oList = List.of("a", "b", "c")] JavaScript: oArray = ["a", "b", "c"] Kotlin: oArray = arrayOf("a", "b", "c") PHP: $oArray = ["a", "b", "c"] Python: oList = ["a", "b", "c"] R: oVec = c("a", "b", "c") Ruby: oArray = ["a", "b", "c"] Rust: oArray = ["a", "b", "c"] [note: can only overwrite an existing array with an array of the same size (unless use 'let')] Scala: oArray = Array("a", "b", "c") [also: oList = List("a", "b", "c")] [FIXME] SQL (MySQL): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c');] [note: clears the table, then adds rows] [FIXME] SQL (PostgreSQL): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c');] [note: clears the table, then adds rows] SQL (SQLite): ___ [can use: DELETE FROM MyTable; INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c');] [note: clears the table, then adds rows] Swift: oArray = ["a", "b", "c"] UFL: (Array.NewEntriesStrDemo) [or Array.NewArrayOfArraysStrDemo/Entries.NewStrDemo/Entries.NewStrStrDemo/Array.NewEntriesStringDemo/Array.NewArrayOfArraysStringDemo/Entries.NewStringDemo][array of arrays, e.g. entries (key-value pairs)] AutoHotkey: oEntries := [["k1","v1"], ["k2","v2"], ["k3","v3"]] C++: std::string oEntries[][2] = {{"k1","v1"}, {"k2","v2"}, {"k3","v3"}} [also: std::vector<std::vector<std::string>> oEntries = {{"k1","v1"}, {"k2","v2"}, {"k3","v3"}}] C#: string[][] oEntries = {new[]{"k1","v1"}, new[]{"k2","v2"}, new[]{"k3","v3"}} Crystal: oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]] Excel: ___ Excel VBA: oEntries = Array(Array("k1", "v1"), Array("k2", "v2"), Array("k3", "v3")) Go: oEntries := [...][2]string{{"k1", "v1"}, {"k2", "v2"}, {"k3", "v3"}} [also (a slice of slices): oEntries := [][]string{{"k1", "v1"}, {"k2", "v2"}, {"k3", "v3"}}] Java: String[][] oEntries = {{"k1","v1"}, {"k2","v2"}, {"k3","v3"}} JavaScript: oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]] Kotlin: oEntries = arrayOf(arrayOf("k1","v1"), arrayOf("k2","v2"), arrayOf("k3","v3")) PHP: $oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]] Python: oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]] R: oEntries = list(list("k1","v1"), list("k2","v2"), list("k3","v3")) [e.g. vValue = unlist(oEntries[1])[1]] Ruby: oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]] Rust: oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]] Scala: oEntries = Array(("k1","v1"), ("k2","v2"), ("k3","v3")) [note: array of tuples] [also (array of arrays): var oEntries = Array(Array("k1","v1"), Array("k2","v2"), Array("k3","v3"))] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]] UFL: (Array.NewAnyDemo) [or Array.NewMultiTypeDemo][create an array containing values of multiple types for testing][note: -0.0: negative zero][see also: Any.NewDemo] AutoHotkey: oArray := ["abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, -Abs(Ln(0)), Abs(Ln(0)), Abs(Ln(0)/Ln(0))] [note: false and 0 are identical] C++: ___ C#: object[] oArray = {"abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, Double.NegativeInfinity, Double.PositiveInfinity, Double.NaN} Crystal: oArray = ["abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, -Float64::INFINITY, Float64::INFINITY, Float64::NAN] Excel: ___ Excel VBA: oArray = Array("abc", "", -123, 0, 123, -123.456, -0#, 0#, 123.456, True, False, vNInf, vInf, vNaN) [note: need to define NInf/Inf/NaN elsewhere] Go: oArray := [...]interface{}{"abc", "", -123, 0, 123, -123.456, -math.Abs(0.0), 0.0, 123.456, true, false, math.Inf(-1), math.Inf(1), math.NaN()} [note: use '[]' instead of '[...]' for a slice] Java: Object[] oArray = {"abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN} JavaScript: oArray = ["abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, -Infinity, Infinity, NaN] Kotlin: oArray = arrayOf("abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN) PHP: $oArray = ["abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, -INF, INF, NAN] Python: oList = ["abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, True, False, float("-inf"), float("inf"), float("nan")] R: ___ [can use: oList = list("abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, TRUE, FALSE, -Inf, Inf, NaN)] [note: vectors coerce values to one type (e.g. character (string)/numeric)] [also: as.integer(vNum)] Ruby: oArray = ["abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, -Float::INFINITY, Float::INFINITY, Float::NAN] Rust: ___ [note: workaround: an array/vector of enums] Scala: oArray = Array("abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, Double.NegativeInfinity, Double.PositiveInfinity, Double.NaN) SQL (MySQL): ___ [WARNING: MySQL often returns NULL where NaN is expected] [see also: SQL Array.NewAnyDemo extra notes] [can use (returns 'json' type): json_extract('["", 0, -0.0, 0.0, false]', '$[0]')] SQL (PostgreSQL): ___ [see also: SQL Array.NewAnyDemo extra notes] [can use (returns 'json' type): '["", 0, -0.0, 0.0, false]'::json -> 0] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v ANY) STRICT; INSERT INTO MyTable (v) VALUES ('abc'), (''), (-123), (0), (123), (-123.456), (-0.0), (0.0), (123.456), (true), (false), (-1e999), (1e999), (NULL); [WARNING: SQLite often returns NULL where NaN is expected] [MAJOR WARNING: attempts to store -0.0 in a table, store 0.0 (or 0)] [see also: SQL Array.NewAnyDemo extra notes] [can use (returns raw value): '["", 0, -0.0, 0.0, false]' ->> 0] Swift: oArray = ["abc", "", -123, 0, 123, -123.456, -0.0, 0.0, 123.456, true, false, -Double.infinity, Double.infinity, Double.nan] as [Any] UFL: (Array.NewAnyFalsyDemo) [or Array.NewMultiTypeFalsyDemo][create an array containing values of multiple types, with values typically considered falsy][note: other values to consider: NaN, null, empty objects, some object types][note: some of these values are considered truthy by some languages][note: some languages don't define whether values are truthy/falsy][note: -0.0: negative zero][see also: Any.NewDemo] AutoHotkey: oArray := ["", 0, -0.0, 0.0, false] [note: false and 0 are identical] C++: ___ C#: object[] oArray = {"", 0, -0.0, 0.0, false} Crystal: oArray = ["", 0, -0.0, 0.0, false] Excel: ___ Excel VBA: oArray = Array("", 0, -0#, 0#, False) Go: oArray := [...]interface{}{"", 0, -math.Abs(0.0), 0.0, false} [note: use '[]' instead of '[...]' for a slice] Java: Object[] oArray = {"", 0, -0.0, 0.0, false} JavaScript: oArray = ["", 0, -0.0, 0.0, false] Kotlin: oArray = arrayOf("", 0, -0.0, 0.0, false) PHP: $oArray = ["", 0, -0.0, 0.0, false] Python: oList = ["", 0, -0.0, 0.0, False] R: ___ [can use: oList = list("", 0, -0.0, 0.0, FALSE)] [note: vectors coerce values to one type (e.g. character (string)/numeric)] [also: as.integer(0)] Ruby: oArray = ["", 0, -0.0, 0.0, false] Rust: ___ [note: workaround an array/vector of enums] Scala: oArray = Array("", 0, -0.0, 0.0, false) SQL (MySQL): ___ [WARNING: MySQL often returns NULL where NaN is expected] [see also: SQL Array.NewAnyDemo extra notes] [can use (returns 'json' type): json_extract('["", 0, -0.0, 0.0, false]', '$[0]')] SQL (PostgreSQL): ___ [see also: SQL Array.NewAnyDemo extra notes] [can use (returns 'json' type): '["", 0, -0.0, 0.0, false]'::json -> 0] SQL (SQLite): CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v ANY) STRICT; INSERT INTO MyTable (v) VALUES (''), (0), (-0.0), (0.0), (false); [WARNING: SQLite often returns NULL where NaN is expected] [MAJOR WARNING: attempts to store -0.0 in a table, store 0.0 (or 0)] [see also: SQL Array.NewAnyDemo extra notes] [can use (returns raw value): '["", 0, -0.0, 0.0, false]' ->> 0] Swift: oArray = ["", 0, -0.0, 0.0, false] as [Any] UFL: (Array.NewSizeDemo) [create an array of size n, the values don't matter][see also: Array.Rept/Range.ToArray/Array.New1ToNDemo] AutoHotkey: (oArray := []).Length := vCount [note: 'no value'-initialised] [also (space-initialised, i.e. 1-char string, Chr(32)): StrSplit(Format("{:" vCount "}", ""))] C++: int* oArray = new int[vCount] [note: zero-initialised] [also ('random'-value-initialised, replace '123' with the required size): int oArray[123]] [also (zero-initialised): int oArray[123] = {}] [also (zero-initialised): std::vector<int> oVec(vCount)] C#: int[] oArray = new int[vCount] [also: var oArray = Enumerable.Repeat(0, vCount).ToArray()] [note: both zero-initialised] [requires (Enumerable): using System.Linq] Crystal: oArray = Array.new(vCount, 0) Excel: ___ Excel VBA: ReDim oArray(0 To vCount - 1) [note: empty-initialised] [note (zero-initialised): ReDim oArray(0 To vCount - 1) As Integer] Go: oSlice := make([]int, vCount) [also (cannot set array size dynamically, replace '123' as appropriate): oArray := [123]int{}] Java: int[] oArray = new int[vCount] [note: zero-initialised] JavaScript: oArray = Array(vCount) [note: empty-initialised (elided)] [also (zero-initialised): oArray = Array(vCount).fill(0)] Kotlin: oArray = IntArray(vCount) [note: zero-initialised] PHP: $oArray = range(0, $vCount-1) [also (zero-initialised): $oArray = array_fill(0, $vCount, 0)] Python: oList = [0] * vCount [note: zero-initialised] R: oVec = 1:vCount [note: the R range is a vector] Ruby: oArray = Array.new(vCount) Rust: oArray = [0; vCount] [beforehand: const vCount: usize = 10] [WARNING: can't set count at runtime] Scala: oArray = Array.fill(vCount)(0) SQL (MySQL): ___ [can use: CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v INTEGER); INSERT INTO MyTable SELECT NULL,0 FROM json_table(concat('[',repeat('0,', MyCount-1),'0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp;] SQL (PostgreSQL): ___ [can use: CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v INTEGER); INSERT INTO MyTable (v) SELECT 0 FROM generate_series(1, MyCount) vTemp;] [also: CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v INTEGER); INSERT INTO MyTable SELECT *,0 FROM generate_series(1, MyCount)] [also: array_fill(0, ARRAY[MyCount])] SQL (SQLite): ___ [can use: CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER); INSERT INTO MyTable SELECT NULL,0 FROM generate_series(1, MyCount);] [also: CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER); INSERT INTO MyTable SELECT NULL,0 FROM json_each('['||replace(hex(zeroblob(MyCount)), '00', '0,')||']');] [also (repeated doubling then truncating), e.g. 1+1+2**7=130 rows, truncated to 100: CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v TEXT); INSERT INTO MyTable DEFAULT VALUES; INSERT INTO MyTable DEFAULT VALUES; INSERT INTO MyTable SELECT NULL, NULL FROM MyTable, MyTable, MyTable, MyTable, MyTable, MyTable, MyTable; DELETE FROM MyTable WHERE rowid>100; UPDATE MyTable SET v=0;] [WARNING: using rowid could be unreliable, but the count can be checked via: SELECT COUNT(*) FROM MyTable] [version: SQLite 3.42: JSON5 support (including trailing comma support)] Swift: oArray = Array(repeating:0, count:vCount) [note: zero-initialised] UFL: (Array.New1ToNDemo) [create an array of size n, with values 1 to n][see also: Array.Rept/Range.ToArray/Array.Keys/Array.NewSizeDemo] AutoHotkey: ___ [can use: oArray := [], oArray.Length := vCount, oArray := [oArray.__Enum(2).Bind(, &_)*]] C++: ___ [can use: std::vector<int> oVec(vCount); std::iota(oVec.begin(), oVec.end(), 1);] [also (replace '123' with the required size): int oArray[123]; std::iota(std::begin(oArray), std::end(oArray), 1);] [requires (iota): #include <numeric>] C#: int[] oArray = Enumerable.Range(1, vCount).ToArray() [requires (Enumerable): using System.Linq] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: oArray = (1..vCount).to_a Excel: ___ Excel VBA: ___ [can use: ReDim oArray(0 To vCount - 1): For i = 1 To vCount: oArray(i - 1) = i: Next i] Go: ___ [can use: oSlice := make([]int, vCount); for i := range oSlice {oSlice[i] = i + 1}] Java: int[] oArray = IntStream.rangeClosed(1, vCount).toArray() [requires (IntStream): import java.util.stream.*] JavaScript: oArray = [...Array(vCount).keys()].map(v=>v+1) Kotlin: oArray = (1..vCount).toList().toTypedArray() PHP: $oArray = range(1, $vCount) Python: oList = list(range(1, vCount+1)) R: oVec = 1:vCount Ruby: oArray = (1..vCount).to_a Rust: oVec = (1..=vCount).collect::<Vec<_>>() Scala: oArray = Range.inclusive(1, vCount).toArray SQL (MySQL): ___ [can use: CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v INTEGER); INSERT INTO MyTable SELECT NULL,vTemp FROM json_table(concat('[',repeat('0,', MyCount-1),'0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp;] SQL (PostgreSQL): ___ [can use: CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v INTEGER); INSERT INTO MyTable (v) SELECT vTemp FROM generate_series(1, MyCount) vTemp;] [also: ARRAY(SELECT generate_series(1, MyCount))] SQL (SQLite): ___ [can use: CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER); INSERT INTO MyTable SELECT NULL,value FROM generate_series(1, MyCount);] [also: CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v INTEGER); INSERT INTO MyTable SELECT NULL,key+1 FROM json_each('['||replace(hex(zeroblob(MyCount)), '00', '0,')||']');] Swift: oArray = Array(1...vCount) UFL: (Array.NewAToZDemo) [create an array of size 26, with values strings 'a' to 'z'][see also: ChrMult/StrSplitAZDemo/Range.New/Array.Map/Array.New1ToNDemo] AutoHotkey: ___ [can use: oTemp := [97], oFunc := (&v) => (v:=Chr(oTemp[1]), ++oTemp[1]<=122+1), oArray := [oFunc*]] C++: ___ [can use: std::string oArray[26]; for (int i=0; i<26; i++) oArray[i] = (std::string){(char)(97+i)};] [WARNING: handles ASCII chars only: (std::string){(char)(97+i)}] C#: oArray = Enumerable.Range(97, 26).Select(v=>Char.ConvertFromUtf32(v)).ToArray() [requires (Enumerable): using System.Linq] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: oArray = (97..122).map{|v|v.chr.to_s} Excel: ___ Excel VBA: ___ [can use: ReDim oArray(0 To 122 - 97): For i = 97 To 122: oArray(i - 97) = ChrW(i): Next i] Go: ___ [can use: oSlice := make([]string, 26); for i := range oSlice {oSlice[i] = string(rune(97 + i))}] Java: String[] oArray = IntStream.rangeClosed(97, 122).mapToObj(v->new String(new int[]{v}, 0, 1)).toArray(String[]::new) [requires (IntStream): import java.util.stream.*] JavaScript: oArray = [...Array(122-97+1).keys()].map(v=>String.fromCodePoint(v+97)) Kotlin: oArray = (97..122).map{Character.toString(it)}.toTypedArray() PHP: $oArray = array_map(fn($v)=>mb_chr($v), range(97, 122)) Python: oList = list(map(chr, range(97, 122+1))) [also: oList = [chr(v) for v in range(97, 122+1)]] R: oVec = mapply(\(v) intToUtf8(v), 97:122) Ruby: oArray = (97..122).map{|v|v.chr(Encoding::UTF_8)} Rust: oVec = (97..=122).into_iter().map(|v| char::from_u32(v as u32).unwrap().to_string()).collect::<Vec<_>>() Scala: oArray = Range.inclusive(97, 122).map(v=>String(Array(v), 0, 1)).toArray SQL (MySQL): ___ [can use: CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v TEXT); INSERT INTO MyTable SELECT NULL,char(96+vTemp) FROM json_table(concat('[',repeat('0,', 26-1),'0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp;] SQL (PostgreSQL): ___ [can use: CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v TEXT); INSERT INTO MyTable (v) SELECT chr(96+vTemp) FROM generate_series(1, 26) vTemp;] [also: ARRAY(SELECT chr(96+v) FROM generate_series(1, 26) v)] SQL (SQLite): ___ [can use: CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v TEXT); INSERT INTO MyTable SELECT NULL,char(96+value) FROM generate_series(1, 26);] Swift: oArray = (97...122).map{String(UnicodeScalar($0)!)} UFL: (Array.TrailingComma) [does array assignment accept a trailing comma?][e.g. oArray = [1, 2, 3,]] AutoHotkey: yes [multiple trailing commas: equivalent to one trailing comma] C++: yes [multiple trailing commas: throws] C#: yes [multiple trailing commas: throws] Crystal: yes [multiple trailing commas: throws] Excel: ___ [note: trailing commas are supported in many functions e.g. SUM()] Excel VBA: no [note: one or more trailing commas throws] [multiple trailing commas: throws] Go: yes [multiple trailing commas: throws] Java: yes [multiple trailing commas: throws] JavaScript: yes [multiple trailing commas: n-1 empty items] [WARNING: 2 or more trailing commas: n trailing commas results in n-1 empty items] [note: 1 trailing comma is ignored] Kotlin: yes [multiple trailing commas: throws] PHP: yes [multiple trailing commas: throws] Python: yes [multiple trailing commas: throws] R: no [note: one or more trailing commas throws] [multiple trailing commas: throws] Ruby: yes [multiple trailing commas: throws] Rust: yes [multiple trailing commas: throws] Scala: no [note: one or more trailing commas throws] [multiple trailing commas: throws] SQL (MySQL): ___ [note: no trailing commas are allowed in arrays in JSON strings (MySQL doesn't support JSON5)] SQL (PostgreSQL): no [multiple trailing commas: throws] [multiple trailing commas: throws] [note: no trailing commas are allowed in arrays in JSON strings (PostgreSQL doesn't support JSON5)] [note: no trailing commas are allowed in arrays created via ARRAY[]] SQL (SQLite): ___ [can use: trailing comma in arrays in JSON5 strings] [version: SQLite 3.42: JSON5 support] Swift: yes [multiple trailing commas: throws] UFL: Array.Rept [or Array.Repeat][create an array of the same value repeated n times][see also: Array.Fill] AutoHotkey: ___ C++: std::fill(oArray, oArray+vCount, vValue) [beforehand: int* oArray = new int[vCount]] [also (array): std::fill(std::begin(oArray), std::end(oArray), vValue)] [also (vector): std::fill(oVec.begin(), oVec.end(), vValue)] [beforehand (vector): std::vector<int> oVec(vCount)] [requires (fill): #include <algorithm>] C#: Array.Fill(oArray, vValue) [beforehand: int[] oArray = new int[vCount]] [also: int[] oArray = Enumerable.Repeat(vValue, vCount).ToArray()] [requires (Enumerable): using System.Linq] Crystal: oArray = Array.new(vCount, vValue) Excel: ___ Excel VBA: ___ Go: ___ Java: int[] oArray = Collections.nCopies(vCount, vValue).stream().mapToInt(v->v).toArray() [also: String[] oArray = Collections.nCopies(vCount, vValue).toArray(new String[0])] [requires (Collections): import java.util.*] [also: java.util.Arrays.fill(oArray, vValue)] [beforehand (fill): int[] oArray = new int[vCount]] JavaScript: oArray = Array(vCount).fill(vValue) [also (ES5): Array.apply(null, Array(vCount)).map(function () {return vValue})] Kotlin: oArray = Array(vCount){vValue} [also: oArray = IntArray(vCount){vValue}] [also: oList = List(vCount){vValue}] PHP: $oArray = array_fill($vIndex, $vCount, $vValue) [e.g. $vIndex = 0 for a 0-based array] [also: $oArray = array_pad([], $vCount, $vValue)] Python: oList = [vValue] * vCount R: oVec = rep(vValue, vCount) Ruby: oArray = Array.new(vCount, vValue) Rust: oVec = vec![vValue; vCount] [also: oVec = (0..vCount).map(|_| vValue).collect::<Vec<_>>()] [also (overwrite existing values): oVec.fill(vValue)] Scala: oArray = Array.fill(vCount)(vValue) SQL (MySQL): ___ [can use: INSERT INTO MyTable SELECT vTemp,MyValue FROM json_table(concat('[',repeat('0,', MyCount-1),'0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp] SQL (PostgreSQL): ___ [can use: INSERT INTO MyTable SELECT vTemp,MyValue FROM generate_series(1, MyCount) vTemp] [also: INSERT INTO MyTable SELECT *,MyValue FROM generate_series(1, MyCount)] [also: array_fill(MyValue, ARRAY[MyCount])] SQL (SQLite): ___ [can use: INSERT INTO MyTable SELECT value,MyValue FROM generate_series(1, MyCount)] [also: INSERT INTO MyTable SELECT key+1,MyValue FROM json_each('['||replace(hex(zeroblob(MyCount)), '00', '0,')||']')] [version: SQLite 3.42: JSON5 support (including trailing comma support)] Swift: oArray = Array(repeating:vValue, count:vCount) UFL: Array.ReptMult [e.g. [1,2,3] to [1,2,3,1,2,3,1,2,3]][create an array of the same value(s) repeated n times] AutoHotkey: ___ C++: ___ C#: oArrayNew = Enumerable.Repeat(oArray, vCount).SelectMany(v=>v).ToArray() [requires (Enumerable): using System.Linq] Crystal: oArrayNew = oArray * vCount [also: oArrayNew = Array.new(vCount, oArray).flatten] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: int[] oArrayNew = Stream.iterate(oArray, v->v).flatMapToInt(IntStream::of).limit(oArray.length*vCount).toArray()] [also: String[] oArrayNew = Stream.iterate(oArray, v->v).flatMap(v->Stream.of(oArray)).limit(oArray.length*vCount).toArray(String[]::new)] [also: int[] oArrayNew = Stream.of(Collections.nCopies(vCount, oArray).stream().toArray(int[][]::new)).flatMapToInt(IntStream::of).toArray()] [also: String[] oArrayNew = Stream.of(Collections.nCopies(vCount, oArray).stream().toArray(String[][]::new)).flatMap(Stream::of).toArray(String[]::new)] JavaScript: oArrayNew = Array(vCount).fill(oArray).flat() Kotlin: oArrayNew = Array(vCount){oArray}.flatten().toTypedArray() [also: oListNew = List(vCount){oList}.flatten()] [also: oArrayNew = generateSequence{oArray.asIterable()}.flatten().take(oArray.size*vCount).toList().toTypedArray()] PHP: $oArrayNew = array_merge(...array_fill(0, $vCount, $oArray)) Python: oListNew = oList * vCount R: oVecNew = rep(oVec, vCount) Ruby: oArrayNew = oArray * vCount [also: oArrayNew = Array.new(vCount, oArray).flatten] Rust: oVecNew = oArray.iter().cycle().take(oVec.len() * vCount).collect::<Vec<_>>() [note: also works with vectors] Scala: ___ [can use: oArrayNew = Array.fill(vCount)(oArray).flatten] [FIXME] SQL (MySQL): ___ [e.g. '1,2,3,1,2,3,1,2,3': UPDATE MyTable SET v=(k-1)%MyCount+1] [FIXME] SQL (PostgreSQL): ___ [e.g. '1,2,3,1,2,3,1,2,3': UPDATE MyTable SET v=(k-1)%MyCount+1] [also: e.g. SELECT ARRAY(SELECT unnest(ARRAY[1,2,3]) FROM generate_series(1, 3))] SQL (SQLite): ___ [e.g. '1,2,3,1,2,3,1,2,3': UPDATE MyTable SET v=(k-1)%MyCount+1] Swift: oArrayNew = Array(repeating:oArray, count:vCount).flatMap{$0} UFL: Array.ReptEach [e.g. [1,2,3] to [1,1,1,2,2,2,3,3,3]][repeat each array element n times] AutoHotkey: ___ C++: ___ C#: oArrayNew = oArray.SelectMany(v=>Enumerable.Repeat(v, vCount)).ToArray() [requires (Enumerable): using System.Linq] Crystal: oArrayNew = oArray.flat_map{|v| Array.new(vCount, v)} Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: int[] oArrayNew = Arrays.stream(oArray).mapToObj(v->Collections.nCopies(vCount, v).stream().mapToInt(v2->v2).toArray()).flatMapToInt(IntStream::of).toArray()] [also: String[] oArrayNew = Arrays.stream(oArray).map(v->Collections.nCopies(vCount, v).stream().toArray(String[]::new)).flatMap(Stream::of).toArray(String[]::new)] JavaScript: oArrayNew = oArray.flatMap(v=>Array(vCount).fill(v)) Kotlin: oArrayNew = oArray.flatMap{v->List(vCount){v}}.toTypedArray() [also: oArrayNew = oArray.flatMap{v->Array(vCount){v}.toList()}.toTypedArray()] PHP: $oArrayNew = array_merge(...array_map(fn($v)=>array_fill(0, $vCount, $v), $oArray)) Python: oListNew = [v for v in oList for i in range(vCount)] R: oVecNew = rep(oVec, each=vCount) Ruby: oArrayNew = oArray.flat_map{|v| Array.new(vCount, v)} Rust: oVecNew = oArray.iter().flat_map(|v| std::iter::repeat(v).take(vCount)).collect::<Vec<_>>() [note: also works with vectors] Scala: ___ [can use: oArrayNew = oArray.flatMap(Array.fill(vCount)(_))] [FIXME] SQL (MySQL): ___ [e.g. '1,1,1,2,2,2,3,3,3': UPDATE MyTable SET v=(k-1)/MyCount+1] [FIXME] SQL (PostgreSQL): ___ [e.g. '1,1,1,2,2,2,3,3,3': UPDATE MyTable SET v=(k-1)/MyCount+1] [also: e.g. SELECT ARRAY(SELECT unnest(array_fill(v, ARRAY[3])) FROM unnest(ARRAY[1,2,3]) v)] SQL (SQLite): ___ [e.g. '1,1,1,2,2,2,3,3,3': UPDATE MyTable SET v=(k-1)/MyCount+1] Swift: oArrayNew = oArray.flatMap{Array(repeating:$0, count:vCount)} UFL: (Array.ReptEach1ToNDemo) [e.g. max=4, count=3: [1,1,1,2,2,2,3,3,3,4,4,4]][repeat values 1 to n] AutoHotkey: ___ C++: ___ C#: oArray = Enumerable.Range(1, vMax).SelectMany(v=>Enumerable.Repeat(v, vCount)).ToArray() [requires (Enumerable): using System.Linq] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: oArray = (1..vMax).flat_map{|v| Array.new(vCount, v)} Excel: ___ Excel VBA: ___ Go: ___ Java: int[] oArrayNew = IntStream.rangeClosed(1, vMax).mapToObj(v->Collections.nCopies(vCount, v).stream().mapToInt(v2->v2).toArray()).flatMapToInt(IntStream::of).toArray() JavaScript: oArray = Array(vMax).fill().flatMap((v,k)=>Array(vCount).fill(k+1)) Kotlin: oArray = (1..vMax).flatMap{v->List(vCount){v}}.toTypedArray() [also: oArray = (1..vMax).flatMap{v->Array(vCount){v}.toList()}.toTypedArray()] PHP: $oArray = array_merge(...array_map(fn($v)=>array_fill(0, $vCount, $v), range(1, $vMax))) Python: oList = [v+1 for v in range(vMax) for i in range(vCount)] R: oVec = rep(1:vMax, each=vCount) [also: oVec = ceiling((1:(vMax*vCount))/vCount)] Ruby: oArray = (1..vMax).flat_map{|v| Array.new(vCount, v)} Rust: oVec = (1..=vMax).into_iter().flat_map(|v| std::iter::repeat(v).take(vCount)).collect::<Vec<_>>() Scala: oArrayNew = Range.inclusive(1, vMax).flatMap(Array.fill(vCount)(_)).toArray [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ [also: e.g. SELECT ARRAY(SELECT unnest(array_fill(v, ARRAY[3])) FROM generate_series(1, 3) v)] SQL (SQLite): ___ Swift: oArray = (1...vMax).flatMap{Array(repeating:$0, count:vCount)} UFL: (Array.Keys) [often equivalent to range (0 to n-1, or 1 to n) to array][see also: Range.ToArray] AutoHotkey: oKeys := [oArray.__Enum(2).Bind(, &_)*] [algorithm: 'Bind(, &_)' fills param 2 and leaves param 1 unchanged, before: 2 params, k/v, after: 1 param, k] C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oKeys.push_back(i) [beforehand: std::vector<int> oKeys] C#: ___ [can use: var oKeys = Enumerable.Range(0, oArray.Length).ToArray()] [requires (Enumerable): using System.Linq] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: ___ [can use: (0...oArray.size).to_a] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: var oKeys = IntStream.range(0, oArray.length).toArray()] JavaScript: oKeys = [...oArray.keys()] [also (returns an iterator): oKeys = oArray.keys()] Kotlin: oKeys = oArray.mapIndexed{k,_->k}.toTypedArray() [also: oKeys = (0..<oArray.count()).toList().toTypedArray()] PHP: $oKeys = array_keys($oArray) Python: ___ [can use: oKeys = list(range(len(oList)))] R: ___ [can use: oKeys = 1:length(oVec)] Ruby: ___ [can use: (0...oArray.length).to_a] Rust: ___ [can use: oKeys = (0..oArray.len()).collect::<Vec<_>>()] Scala: ___ [can use: oKeys = Range(0, oArray.length).toArray] SQL (MySQL): SELECT k FROM MyTable SQL (PostgreSQL): SELECT k FROM MyTable [also: SELECT k FROM unnest(MyArray) WITH ORDINALITY AS t(v, k)] SQL (SQLite): SELECT k FROM MyTable Swift: oKeys = oArray.enumerated().map{$0.0} [note: failed with $0] UFL: (Array.Values) [often equivalent to copying an array][see also: Array.Clone] AutoHotkey: oValues := [oArray*] [also: oValues := oArray.Clone()] C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oValues.push_back(oArray[i]) [beforehand: std::vector<std::string> oValues] C#: ___ [can use: var oValues = oArray.Clone() as string[]] [note: replace 'string[]' with the appropriate type] Crystal: ___ [can use (clone array): oValues = oArray.clone] [also: oValues = oArray.dup] Excel: ___ Excel VBA: ___ [can use (clone array): oValues = oArray] Go: ___ [can use (clone array): oValues := oArray] Java: ___ [can use: var oValues = oArray.clone()] JavaScript: oValues = [...oArray.values()] [also (returns an iterator): oValues = oArray.values()] [also: oValues = oArray.slice()] Kotlin: ___ [can use: oValues = oArray.copyOf()] PHP: $oValues = array_values($oArray) [also (clone array): $oValues = $oArray] Python: ___ [can use: oValues = oList.copy()] R: ___ [can use (clone vector): oValues = oVec] Ruby: ___ [can use (clone array): oValues = oArray.clone] [also: oValues = oArray.dup] Rust: ___ [can use: oValues = oArray.clone()] Scala: ___ [can use: oValues = oArray.clone] SQL (MySQL): SELECT v FROM MyTable SQL (PostgreSQL): SELECT v FROM MyTable SQL (SQLite): SELECT v FROM MyTable Swift: oValues = oArray.map{$0} [also (clone array): oValues = oArray] UFL: (Array.Entries) [or Array.ToEntries][array to entries (key-value pairs)] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oEntries.push_back(std::make_pair(i, oArray[i])) [beforehand: std::vector<std::pair<int,std::string>> oEntries] C#: Tuple<int,string>[] oEntries = oArray.Select((v,k)=>new Tuple<int,string>(k,v)).ToArray() [also: KeyValuePair<int,string>[] oEntries = oArray.Select((v,k)=>new KeyValuePair<int,string>(k,v)).ToArray()] [also: string[][] oEntries = oArray.Select((v,k)=>new[]{k.ToString(),v}).ToArray()] [requires (KeyValuePair): using System.Collections.Generic] Crystal: oEntries = oArray.each_with_index.map{|v,k| {k,v}}.to_a Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) oEntries[i] = Map.entry(i, oArray[i]) [beforehand: Map.Entry<Integer,String>[] oEntries = new Map.Entry[oArray.length]] [also (indexes as strings): for (int i=0; i<oArray.length; i++) oEntries[i] = new String[]{"" + i, oArray[i]}] [beforehand (indexes as strings): String[][] oEntries = new String[oArray.length][2]] [also (int[]/String[]): oArrayNew = IntStream.range(0, oArray.length).mapToObj(i->Map.entry(i, oArray[i])).toArray()] [requires (Map): import java.util.*] JavaScript: oEntries = [...oArray.entries()] [note: returns an array of arrays] [also (returns an iterator): oEntries = oArray.entries()] Kotlin: oEntries = oArray.mapIndexed{k,v->k to v!!}.toMap().entries PHP: foreach ($oArray as $vKey=>$vValue) array_push($oEntries, [$vKey, $vValue]) [beforehand: $oEntries = []] [also: $oEntries = array_map(function($oKey) use ($oArray) {return [$oKey, $oArray[$oKey]];}, array_keys($oArray))] Python: oEntries = {k:v for k,v in enumerate(oList)}.items() R: oEntries = Map(c, 1:length(oVec), oVec, USE.NAMES=FALSE) [note: 1-based] [also (0-based): oEntries = Map(c, 0:(length(oVec)-1), oVec, USE.NAMES=FALSE)] Ruby: oEntries = oArray.each_with_index.map{|v,k| [k,v]} Rust: oEntries = oArray.iter().enumerate().collect::<Vec<_>>() Scala: oEntries = oArray.zipWithIndex [note: an array of tuples] [also (array of arrays): oEntries = oArray.zipWithIndex.map((v,k)=>Array(k,v))] SQL (MySQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] SQL (PostgreSQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] SQL (SQLite): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] Swift: oEntries = oArray.enumerated().map{[$0,$1]} [also (to tuples): oEntries = oArray.enumerated().map{($0,$1)}] UFL: Array.Flat [or Array.Flatten][e.g. array of arrays to array][note: modifies the array][see also (inverse): Array.Chunk][see also: Array.FlatMap] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ [can use: oArray = oArray.flatten] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oArray.flat(vDepth) [note: default depth: 1] Kotlin: oArray.flatten() PHP: ___ Python: ___ [can use: oListNew = reduce(list.__add__, oList)] [requires: from functools import reduce] [also: oListNew = list(itertools.chain.from_iterable(oList))] [requires: import itertools] [note (both): flattens by depth 1] R: ___ Ruby: oArray.flatten! Rust: ___ Scala: ___ [can use: oArray = oArray.flatten] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use (flatten multi-dimensional array to 1D array): unnest(MyArray)] SQL (SQLite): ___ Swift: ___ UFL: Array.Flattened [e.g. array of arrays to array][note: doesn't modify the array (creates a new array)] AutoHotkey: ___ C++: ___ [e.g. flatten array of arrays: for (const auto& oEntry : oEntries) oVec.insert(oVec.end(), oEntry, oEntry+2)] [beforehand (e.g.): std::vector<std::string> oVec] [beforehand (e.g.) std::vector<int> oVec] C#: oArrayNew = oArray.SelectMany(v=>v) Crystal: oArrayNew = oArray.flatten Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [e.g. flatten String[][]: String[] oArray = Arrays.stream(oEntries).flatMap(Arrays::stream).toArray(String[]::new)] [e.g. flatten int[][]: int[] oArray = Arrays.stream(oEntries).flatMapToInt(Arrays::stream).toArray()] [also: String[] oArray = Stream.of(oEntries).flatMap(Stream::of).toArray(String[]::new)] [also: int[] oArray = Stream.of(oEntries).flatMapToInt(IntStream::of).toArray()] JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: oArrayNew = oArray.flatten Rust: ___ [can use (vector of vectors): oVecNew = oEntries.clone().into_iter().flatten().collect::<Vec<_>>()] [can use (array of arrays, vector of vectors): for oEntry in oEntries.clone() {for vValue in oEntry {oVecNew.push(vValue);}}] [beforehand (a of a, v of v): let mut oVecNew: Vec<&str> = vec![]] Scala: oArrayNew = oArray.flatten SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use (flatten multi-dimensional array to 1D array): unnest(MyArray)] SQL (SQLite): ___ Swift: oArrayNew = oArray.flatMap{$0} [WARNING: only flattens by 1 level] UFL: Array.Length [or Array.Size/Array.CountSimple][get length/count/size (element count)] AutoHotkey: oArray.Length [deprecated (AHK v1): oArray.Length()] C++: sizeof(oArray)/sizeof(oArray[0]) [also: vLen = *(&oArray+1) - oArray] [note (std::vector): oVec.size()] [also: vLen = std::end(oArray) - std::begin(oArray)] C#: oArray.Length [also: oList.Count] Crystal: oArray.size Excel: ___ Excel VBA: vLen = UBound(oArray) - LBound(oArray) + 1 [note: this works for empty arrays too, e.g. Array() has UBound -1 and LBound 0] Go: len(oArray) Java: oArray.length [also: oList.size()] [WARNING: oArray.length requires no parentheses, unlike vText.length()] JavaScript: oArray.length Kotlin: oArray.size [also: oArray.count()] PHP: count($oArray) [also: sizeof($oArray)] Python: len(oList) R: length(oVec) [also: length(oList)] Ruby: oArray.length [also: oArray.size] [also: oArray.count] Rust: oArray.len() [also: oVec.len()] Scala: oArray.length [also: oArray.size] [also: oList.length] [also: oList.size] SQL (MySQL): SELECT COUNT(*) FROM MyTable [WARNING: COUNT(MyCol) excludes nulls, COUNT(*) counts all rows] SQL (PostgreSQL): SELECT COUNT(*) FROM MyTable [WARNING: COUNT(MyCol) excludes nulls, COUNT(*) counts all rows] [also: cardinality(MyArray)] [also: coalesce(array_length(MyArray, 1), 0)] [also: coalesce(array_upper(MyArray, 1), 0)] [WARNNG: for an empty array, array_length(MyArray, 1), and, array_upper(MyArray, 1), return NULL, use coalesce() as a workaround] SQL (SQLite): SELECT COUNT(*) FROM MyTable [WARNING: COUNT(MyCol) excludes nulls, COUNT(*) counts all rows] Swift: oArray.count UFL: Array.CountNonNull [count items with a value][e.g. check if array is dense][see also: Array.FilterRemoveNull] AutoHotkey: ___ C++: for (const auto& vValue : oArray) if (vValue != (std::string)NULL) vCount++ [beforehand: int vCount = 0] C#: vCount = oArray.Count(v=>v!=null) Crystal: vCount = oArray.count{|v| v!=nil} Excel: ___ Excel VBA: ___ [note: can use Filter() to list matches(/non-matches) that are a *substring* of a needle, case-sensitive/case-insensitive (integer values are treated as strings)] Go: ___ Java: ___ [e.g. Integer[]: int vCount = Arrays.stream(oArray).reduce(0,(a,v)->a+(v!=null?1:0))] JavaScript: ___ Kotlin: ___ PHP: $vCount = count(array_filter($oArray, function($oValue) {return ($oValue != null);})) Python: vCount = sum(1 for v in oList if v is not None) R: vCount = length(na.omit(oVec)) [count elements excluding any NA elements] Ruby: vCount = oArray.count{|v| v!=nil} Rust: vCount = oArray.iter().fold(0, |a,v| a+(*v).is_none() as i32) Scala: ___ [can use: oArray.count(_!=null)] SQL (MySQL): SELECT COUNT(*) FROM MyTable WHERE v IS NOT NULL [also: SELECT COUNT(v) FROM MyTable] [e.g. SELECT COUNT(vTemp) FROM json_table(CAST(json_array(1, 2, 3, NULL) AS CHAR), '$[*]' columns(vTemp INT PATH '$')) oTemp] [note: json_array() keeps nulls in MySQL/SQLite, but not in PostgreSQL] SQL (PostgreSQL): SELECT COUNT(*) FROM MyTable WHERE v IS NOT NULL [also: SELECT COUNT(v) FROM MyTable] [e.g. SELECT COUNT(vTemp) FROM json_table(json_build_array(1, 2, 3, NULL), '$[*]' columns(vTemp INT PATH '$')) oTemp] [MAJOR WARNING: json_array() removes nulls in PostgreSQL, but not in MySQL/SQLite, json_build_array() keeps nulls] [also: SELECT count(v) FROM unnest(MyArray) v] [WARNING: counts all values including nulls: SELECT count(*) FROM unnest(MyArray)] SQL (SQLite): SELECT COUNT(*) FROM MyTable WHERE v IS NOT NULL [also: SELECT COUNT(v) FROM MyTable] [e.g. SELECT COUNT(value) FROM json_each(json_array(1, 2, 3, NULL))] [note: json_array() keeps nulls in MySQL/SQLite, but not in PostgreSQL] Swift: vCount = oArray.reduce(0){$0+($1==nil ?1:0)} [note: if '?' 'has no whitespace on the left, it's treated as a postfix operator'] UFL: Array.Count [or Array.CountMatch][1 param: count items that match predicate (i.e. like Array.Filter but the count only, not the matches)][see also: Array.Filter/Array.Reduce] AutoHotkey: ___ C++: ___ [can use: vCount = std::accumulate(oVec.begin(), oVec.end(), 0, [vNeedle](int a,int v){return a+(v==vNeedle);})] [also: for (const auto& vValue : oArray) if (vValue == vNeedle) vCount++] [beforehand: int vCount = 0] [requires: #include <numeric>] C#: vCount = oArray.Count(oFunc) [also: vCount = oArray.Count(v=>oFunc(v))] Crystal: vCount = oArray.count(&oFunc) [also: vCount = oArray.count{|v| oFunc.call(v)}] Excel: ___ Excel VBA: ___ [note: can use Filter() to list matches(/non-matches) that are a *substring* of a needle, case-sensitive/case-insensitive (integer values are treated as strings)] Go: ___ Java: ___ [can use (int[]): int vCount = Arrays.stream(oArray).boxed().reduce(0,(a,v)->a+(v==vNeedle?1:0))] [also (int[]): long vCount = Arrays.stream(oArray).boxed().filter(v->v==vNeedle).count()] [can use (String[]): int vCount = Arrays.stream(oArray).reduce(0,(a,v)->a+(v==vNeedle?1:0),Integer::sum)] [also (String[]): long vCount = Arrays.stream(oArray).filter(v->v==vNeedle).count()] JavaScript: ___ [can use: vCount = oArray.reduce((a,v)=>a+(v==vNeedle), 0)] [also: vCount = oArray.filter(oFunc).length] Kotlin: vCount = oArray.count(oFunc) PHP: ___ [can use: $vCount = array_reduce($oArray, fn($a,$v)=>$a+($v==$vNeedle))] [also: $vCount = count(array_filter($oArray, function($oValue) use ($vNeedle) {return ($oValue == $vNeedle);}))] Python: ___ [can use: vCount = reduce(lambda a,v:a+(v==vNeedle), oList, 0)] [also: vCount = len(list(filter(oFunc, oList)))] [requires (reduce): from functools import reduce] [also: vCount = sum(1 for v in oList if oFunc(v))] R: ___ [can use: vCount = Reduce(\(a,v) a+(v==vNeedle), oVec, 0)] [also: vCount = length(Filter(oFunc, oVec))] [also (unusual syntax): vCount = length(oVec[oFunc(oVec)])] [e.g. (unusual syntax): vCount = length(oVec[oVec%%3 == 0])] [note: Filter() excludes NA values] Ruby: vCount = oArray.count(&oFunc) [also: vCount = oArray.count{|v| oFunc.call(v)}] Rust: ___ [can use: vCount = oArray.iter().fold(0, |a,v| a+(*v==vNeedle) as i32)] [also: vCount = oArray.iter().filter(|v| oFunc(**v)).count()] Scala: vCount = oArray.count(oFunc) [also: vCount = oArray.count(_==vNeedle)] [also: vCount = oArray.count(v=>v==vNeedle)] [FIXME] SQL (MySQL): ___ [e.g. SELECT COUNT(*) FROM MyTable WHERE v=MyValue] [FIXME] SQL (PostgreSQL): ___ [e.g. SELECT COUNT(*) FROM MyTable WHERE v=MyValue] SQL (SQLite): ___ [e.g. SELECT COUNT(*) FROM MyTable WHERE v==MyValue] Swift: ___ [can use: vCount = oArray.reduce(0){$0+($1==vNeedle ?1:0)}] [also: vCount = oArray.filter(oFunc).count] UFL: (Array.AllAnyNoneMethods) [list the method names for All/Any/None equivalents, if available][note: None is equivalent to !Any][see also: Array.All/Array.Any/Array.None] AutoHotkey: ___/___/___ C++: std::all_of/std::any_of/std::none_of [requires (all_of/any_of/none_of): #include <algorithm>] C#: All/Any/___ [also: TrueForAll/Exists/___] [requires (All/Any): using System.Linq] Crystal: all/any/none Excel: ___/___/___ Excel VBA: ___/___/___ Go: ___/___/___ Java: allMatch/anyMatch/noneMatch JavaScript: every/some/___ Kotlin: all/any/none PHP: array_all/array_any/___ Python: all/any/___ R: all/any/___ Ruby: all/any/none Rust: all/any/___ Scala: forall/exists/___ [FIXME] SQL (MySQL): ___/___/___ [FIXME] SQL (PostgreSQL): ___/___/___ SQL (SQLite): ___/___/___ Swift: allSatisfy/contains/___ UFL: Array.All [check that all items match the predicate][see also: Array.Count/Array.Any] AutoHotkey: ___ C++: std::all_of(std::begin(oArray), std::end(oArray), oFunc) [requires (all_of): #include <algorithm>] C#: oArray.All(oFunc) [also: Array.TrueForAll(oArray, oFunc)] [requires (All): using System.Linq] Crystal: oArray.all?(&oFunc) [also: oArray.all?{|v| oFunc.call(v)}] Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.stream(oArray).allMatch(oFunc) JavaScript: oArray.every(oFunc) Kotlin: oArray.all(oFunc) [also: oArray.all{oFunc(it)}] PHP: array_all($oArray, $oFunc) Python: all(oFunc(v) for v in oList) R: all(oFunc(oVec)) [also: all(oVecBool)] [e.g. all(oVec%%3 == 0)] [e.g. all(c(1,2,3)%%3 == 0)] [e.g. all(c(TRUE,TRUE,FALSE))] Ruby: oArray.all?(&oFunc) [also: oArray.all?{|v| oFunc.call(v)}] Rust: oArray.iter().all(|&v| oFunc(v)) Scala: oArray.forall(oFunc) [also: oArray.forall(oFunc(_))] [FIXME] SQL (MySQL): ___ [e.g. no non-match, means all match: SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE NOT v=MyValue)] [FIXME] SQL (PostgreSQL): ___ [e.g. no non-match, means all match: SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE NOT v=MyValue)] SQL (SQLite): ___ [e.g. no non-match, means all match: SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE NOT v==MyValue)] Swift: oArray.allSatisfy(oFunc) [also: oArray.allSatisfy{oFunc($0)}] [also: !oArray.contains(where:{!oFunc($0)})] [note: i.e. where it doesn't contain a non-match] UFL: Array.Any [check that at least 1 item matches the predicate][see also: Array.Count/Array.All/Array.HasVal/Array.IndexOf] AutoHotkey: ___ C++: std::any_of(std::begin(oArray), std::end(oArray), oFunc) [requires (any_of): #include <algorithm>] C#: oArray.Any(oFunc) [also: Array.Exists(oArray, oFunc)] [requires (Any): using System.Linq] Crystal: oArray.any?(&oFunc) [also: oArray.any?{|v| oFunc.call(v)}] Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.stream(oArray).anyMatch(oFunc) JavaScript: oArray.some(oFunc) Kotlin: oArray.any(oFunc) [also: oArray.any{oFunc(it)}] PHP: array_any($oArray, $oFunc) Python: any(oFunc(v) for v in oList) R: any(oFunc(oVec)) [also: any(oVecBool)] [e.g. any(c(1,2,3)%%3 == 0)] [e.g. any(c(TRUE,TRUE,FALSE))] Ruby: oArray.any?(&oFunc) [also: oArray.any?{|v| oFunc.call(v)}] Rust: oArray.iter().any(|&v| oFunc(v)) Scala: oArray.exists(oFunc) [also: oArray.exists(oFunc(_))] SQL (MySQL): ___ [e.g. at least one match: SELECT 0 != COUNT(*) FROM MyTable WHERE v=MyValue] SQL (PostgreSQL): ___ [e.g. at least one match: SELECT 0 != COUNT(*) FROM MyTable WHERE v=MyValue] SQL (SQLite): ___ [e.g. at least one match: SELECT 0 != COUNT(*) FROM MyTable WHERE v==MyValue] Swift: oArray.contains(where:oFunc) UFL: Array.None [check that no items match the predicate][see also: Array.Count/Array.All] AutoHotkey: ___ C++: std::none_of(std::begin(oArray), std::end(oArray), oFunc) [requires (none_of): #include <algorithm>] C#: ___ [can use: !oArray.Any(oFunc)] [also: !Array.Exists(oArray, oFunc)] [requires (Any): using System.Linq] Crystal: oArray.none?(&oFunc) [also: oArray.none?{|v| oFunc.call(v)}] Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.stream(oArray).noneMatch(oFunc) JavaScript: ___ [can use: !oArray.some(oFunc)] Kotlin: oArray.none(oFunc) [also: oArray.none{oFunc(it)}] PHP: ___ [can use: !array_any($oArray, $oFunc)] Python: ___ [can use: not any(oFunc(v) for v in oList)] R: ___ [can use: !any(oFunc(oVec))] [also: !any(oVecBool)] Ruby: oArray.none?(&oFunc) [also: oArray.none?{|v| oFunc.call(v)}] Rust: ___ [can use: !oArray.iter().any(|&v| oFunc(v))] Scala: ___ [can use: !oArray.exists(oFunc)] [FIXME] SQL (MySQL): ___ [e.g. not one match: SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE v=MyValue)] [FIXME] SQL (PostgreSQL): ___ [e.g. not one match: SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE v=MyValue)] SQL (SQLite): ___ [e.g. not one match: SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE v==MyValue)] Swift: ___ [can use: !oArray.contains(where:oFunc)] UFL: Array.AllEqual [or Array.AreEqual][check that all items are equal to each other][note: all return true for an empty array][note: if using an 'All' method, can skip the first item, since it is equal to itself][note: a simple algorithm is to compare every value to the first value][see also: Array.All/Array.First/Array.Distinct/Array.Length/All.Count] AutoHotkey: ___ C++: vAreEqual = std::all_of(std::begin(oArray), std::end(oArray), [&oArray](int v){return v==oArray[0];}) [requires (all_of): #include <algorithm>] [WARNING: oArray[0] will give a compile time error if the array is empty (but oVec[0] for an empty vector will not cause an error)] C#: vAreEqual = oArray.Skip(1).All(v=>v==oArray[0]) [also: vAreEqual = Array.TrueForAll(oArray, v=>v==oArray[0])] [requires (All): using System.Linq] Crystal: vAreEqual = oArray.all?{|v|v==oArray[0]} [also: vAreEqual = oArray.each_cons(2).all?{|v|v[0]==v[1]}] [also: each_cons_pair()] Excel: ___ Excel VBA: ___ Go: ___ Java: vAreEqual = Arrays.stream(oArray).allMatch(v->v==oArray[0]) [WARNING: if oArray is not final/effectively final, you can't use it in a lambda function, workaround: clone oArray, and refer to the clone] [requires (Arrays): import java.util.*] JavaScript: vAreEqual = oArray.every(v=>v===oArray[0]) Kotlin: vAreEqual = oArray.all{it==oArray[0]} PHP: $vAreEqual = array_all($oArray, fn($v)=>$v===$oArray[0]) Python: vAreEqual = all(v==oList[0] for v in oList) R: vAreEqual = all(oVec==oVec[1]) Ruby: vAreEqual = oArray.all?{|v|v==oArray[0]} [also: vAreEqual = oArray.each_cons(2).all?{|v1,v2|v1==v2}] Rust: vAreEqual = oArray.iter().all(|&v|v==oArray[0]) [WARNING: oArray[0] will give a compile time error if the array is empty (but oVec[0] for an empty vector will not cause an error)] Scala: vAreEqual = oArray.forall(_==oArray(0)) SQL (MySQL): SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE NOT v=(SELECT v FROM MyTable LIMIT 1)) [algorithm: no non-match, means all match] SQL (PostgreSQL): SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE NOT v=(SELECT v FROM MyTable LIMIT 1)) [algorithm: no non-match, means all match] SQL (SQLite): SELECT COUNT(*) WHERE NOT EXISTS (SELECT 1 FROM MyTable WHERE NOT v==(SELECT v FROM MyTable LIMIT 1)) [algorithm: no non-match, means all match] Swift: vAreEqual = oArray.allSatisfy{$0==oArray[0]} UFL: Array.GetCapacity [get array capacity][see also: StrGetCapacity] AutoHotkey: vCapacity := oArray.Capacity C++: vCapacity = oVec.capacity() C#: vCapacity = oList.Capacity Crystal: ___ [can use: oArray.remaining_capacity] Excel: ___ Excel VBA: ___ Go: vCapacity := cap(oSlice) Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: vCapacity = oArray.capacity() Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vCapacity = oArray.capacity UFL: Array.SetCapacity [set array capacity (or request a minimum capacity)][see also: StrSetCapacity] AutoHotkey: oArray.Capacity := vCapacity C++: oVec.reserve(vCapacity) [also: oVec.shrink_to_fit()] C#: oList.Capacity = vCapacity Crystal: ___ [can use (for new arrays): oArray(Int32).new(vCapacity)] Excel: ___ Excel VBA: ___ Go: oSlice = slices.Grow(oSlice, vCapacityToAdd) [WARNING: value is capacity to *add*, not the future total] [also (shrink to fit): oSlice = slices.Clip(oSlice)] Java: oList.ensureCapacity(vCapacity) [also: oList.trimToSize()] JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ [WARNING (reserve): value is capacity to *add*, not the future total] [e.g. add: oArray.reserve(vCapacityExtra)] [e.g. set total: oArray.reserve(vCapacity-oArray.len())] [also: reserve_exact/shrink_to_fit/shrink_to/truncate] Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray.reserveCapacity(vCapacity) UFL: Array.Has [or Array.HasKey][i.e. is the *index* within bounds] AutoHotkey: vHasKey := oArray.Has(vKey) [deprecated (AHK v1): oArray.HasKey(vKey)] C++: vHasKey = (vKey < sizeof(oArray)/sizeof(oArray[0])) [also: (oArray[vKey] != (std::string)NULL)] C#: vHasKey = (vKey < oArray.Length) [also: (oArray[vKey] != null)] Crystal: vHasKey = (vKey < oArray.size) [also: oArray.count] Excel: ___ Excel VBA: vHasKey = (TypeName(oArray(vKey)) != "Empty") [also: vHasKey = (LBound(oArray) <= vKey) And (vKey <= UBound(oArray))] Go: vHasKey := (vKey < len(oArray)) Java: var vHasKey = (vKey < oArray.length) [also: (oArray[vKey] != null)] JavaScript: vHasKey = (vKey in oArray) [note: empty (elided) items return false, undefined/null items return true] Kotlin: vHasKey = (vKey < oArray.size) [also: (oArray[vKey] != null)] PHP: $vHasKey = array_key_exists($vKey, $oArray) Python: vHasKey = (vKey < len(oList)) [also: (oList[vKey] is not None)] R: vHasKey = (vKey <= length(oVec)) [also: vHasKey = !is.na(oVec[vKey])] [note: 1-based] Ruby: vHasKey = (vKey < oArray.length) [also: oArray.size] [also: oArray.count] Rust: vHasKey = (vKey < oArray.len()) [also: vHasKey = (vKey < oVec.len())] [also: !oArray[vKey].is_none()] [also: !oVec[vKey].is_none()] [also: is_some()] Scala: vHasKey = (vKey < oArray.length) [also: (oArray(vKey) != null)] SQL (MySQL): SELECT 0 != COUNT(*) FROM MyTable WHERE k=MyKey SQL (PostgreSQL): SELECT 0 != COUNT(*) FROM MyTable WHERE k=MyKey [also: MyKey <= cardinality(MyArray)] SQL (SQLite): SELECT 0 != COUNT(*) FROM MyTable WHERE k==MyKey Swift: vHasKey = (vKey < oArray.count) [also: oArray[vKey] != nil] UFL: (Array.KeyIsEmpty) [for a given key, is it empty (non-existent) or null] AutoHotkey: ___ [can use: IsSet(vVar)] [note: cannot use IsSet(oArray[vKey])] [can use: try oArray[vKey]] C++: vKeyIsEmpty = (oArray[vKey] == (std::string)NULL) C#: vKeyIsEmpty = (oArray[vKey] == null) Crystal: vKeyIsEmpty = (oArray[vKey] == nil) Excel: ___ Excel VBA: vKeyIsEmpty = (TypeName(oArray(vKey)) = "Empty") Go: ___ Java: var vKeyIsEmpty = (oArray[vKey] == null) JavaScript: vKeyIsEmpty = !(vKey in oArray) [note: 'vKey in oArray': empty (elided) items return false, undefined/null items return true] [note: 'oArray[oArray.length+n] = v', for n>=0, is a way to create n empty (elided) items] Kotlin: vKeyIsEmpty = (oArray[vKey] == null) PHP: $vKeyIsEmpty = ($oArray[$vKey] == null) Python: vKeyIsEmpty = (oList[vKey] is None) [inverse: (oList[vKey] is not None)] R: vKeyIsEmpty = is.na(oVec[vKey]) Ruby: vKeyIsEmpty = (oArray[vKey] == nil) Rust: vKeyIsEmpty = oArray[vKey].is_none() [also: vKeyIsEmpty = oVec[vKey].is_none()] Scala: vKeyIsEmpty = (oArray(vKey) == null) SQL (MySQL): SELECT COUNT(*) FROM MyTable WHERE k=MyKey AND v IS NULL SQL (PostgreSQL): SELECT COUNT(*) FROM MyTable WHERE k=MyKey AND v IS NULL SQL (SQLite): SELECT COUNT(*) FROM MyTable WHERE k==MyKey AND v IS NULL Swift: vKeyIsEmpty = (oArray[vKey] == nil) UFL: Array.HasVal [or Array.HasValue/Array.Contains][array contains/includes value (value exists)][see also: Array.IndexOf/Array.Any/Array.Find] AutoHotkey: ___ C++: auto vHasVal = (std::find(std::begin(oArray), std::end(oArray), vNeedle) == std::end(oArray)) [also: auto vHasVal = (std::find(oVec.begin(), oVec.end(), vNeedle) == oVec.end())] C#: vHasVal = oArray.Contains(vNeedle) [also: vHasVal = Array.Exists(oArray, v=>v==vNeedle)] Crystal: vHasVal = oArray.includes?(vNeedle) Excel: ___ Excel VBA: ___ [note: can use Filter() to list matches(/non-matches) that are a *substring* of a needle, case-sensitive/case-insensitive (integer values are treated as strings)] Go: vHasVal := slices.Contains(oSlice, vNeedle) Java: ___ [can use: var vHasVal = (oList.indexOf(vNeedle) != -1)] [also (String[]): var vHasVal = Arrays.asList(oArray).contains(vNeedle)] [also (String[]): var vHasVal = Arrays.stream(oArray).anyMatch(vNeedle::equals)] [also (int[]): var vHasVal = IntStream.of(oArray).anyMatch(v->v==vNeedle)] JavaScript: vHasVal = oArray.includes(vNeedle) [note (classList): vHasClass = oElt.classList.contains(vClassName)] Kotlin: vHasVal = oArray.contains(vNeedle) PHP: $vHasVal = in_array($vNeedle, $oArray) Python: vHasVal = vNeedle in oList [inverse: vNeedle not in oList] [also (throws if no match): vKey = oList.index(vNeedle)] [note: word order: 'not in' versus 'is not'] R: vHasVal = vNeedle %in% oVec [also: vHasVal = is.element(vNeedle, oVec)] [note (both): also works with lists] Ruby: vHasVal = oArray.include?(vNeedle) [also: vHasVal = oArray.member?(vNeedle)] Rust: vHasVal = oArray.contains(vNeedle) [also: vHasVal = oVec.contains(vNeedle)] Scala: vHasVal = oArray.contains(vNeedle) [note: also works with lists] SQL (MySQL): SELECT 0 != COUNT(*) FROM MyTable WHERE v=MyValue [also: e.g. SELECT 'abc' IN ('abc', 'def', 'ghi')] SQL (PostgreSQL): SELECT 0 != COUNT(*) FROM MyTable WHERE v=MyValue [also: e.g. SELECT 'abc' IN ('abc', 'def', 'ghi')] [also: MyArray @> ARRAY[MyValue]] [also: array_position(MyArray, MyValue) IS NOT NULL] SQL (SQLite): SELECT 0 != COUNT(*) FROM MyTable WHERE v==MyValue [also: e.g. SELECT 'abc' IN ('abc', 'def', 'ghi')] Swift: vHasVal = oArray.contains(vNeedle) UFL: Array.IndexOf [potentially also: Array.IndexOf0B/Array.IndexOf1B/Array.IndexOfZB/Array.IndexOfUB][get index of first item that matches needle][note: typically returns -1 (0-based) or 0 (1-based) if no match][see also: Array.HasVal/Array.Any/Array.Find/Array.FindIndex] AutoHotkey: ___ C++: auto vIndex = std::find(std::begin(oArray), std::end(oArray), vNeedle) - oArray [also: auto vIndex = std::find(oVec.begin(), oVec.end(), vNeedle) - oVec.begin()] [note (both): returns array length (or vector size) if no match] C#: vKey = Array.IndexOf(oArray, vNeedle) [note: returns -1 if no match ('the lower bound of the array minus 1')] Crystal: vKey = oArray.index(vNeedle) || -1 [note: index() returns nil if no match] Excel: ___ Excel VBA: ___ Go: vKey := slices.Index(oSlice, vNeedle) [note: returns -1 if no match] Java: vKey = oList.indexOf(vNeedle) [note: returns -1 if no match] JavaScript: vKey = oArray.indexOf(vNeedle) [note: returns -1 if no match] Kotlin: vKey = oArray.indexOf(vNeedle) [note: returns -1 if no match] PHP: $vKey = array_search($vNeedle, $oArray) [WARNING: returns false if no match] [note: since PHP arrays are associative arrays, -1 is a valid key name, hence boolean false is returned if no match] Python: vKey = oList.index(vNeedle) [WARNING: throws if no match] [also (returns -1 if no match): vKey = next((k for k,v in enumerate(oList) if v==vNeedle), -1)] [also (returns -1 if no match): vKey = oList.index(vNeedle) if vNeedle in oList else -1] R: vKey = match(vNeedle, oVec) [note: 1-based] [note: returns NA if no match] [also (returns 0 if no match): vKey = match(vNeedle, oVec, nomatch=0)] Ruby: vKey = oArray.index(vNeedle) || -1 [note: index() returns nil if no match] Rust: oOpt = oArray.iter().position(|&v| v==vNeedle) [e.g. vIsMatch = oOpt.is_some()] [e.g. vValue = oOpt.unwrap_or(vDefault)] [e.g. vValue = oOpt.unwrap()] [also: vKey: i32 = oArray.iter().position(|&v| v==vNeedle).map_or(-1, |v| v as i32)] [note: also works with vectors] Scala: vKey = oArray.indexOf(vNeedle) [note: returns -1 if no match] [note: also works with lists] SQL (MySQL): SELECT min(k) FROM MyTable WHERE v=MyNeedle [note: returns NULL if no match] SQL (PostgreSQL): SELECT min(k) FROM MyTable WHERE v=MyNeedle [also: array_position(MyArray, MyNeedle)] [note (both): returns NULL if no match] [also (get indexes of all matches): array_positions()] SQL (SQLite): SELECT min(k) FROM MyTable WHERE v==MyNeedle [note: returns NULL if no match] Swift: oOpt = oArray.firstIndex(of:vNeedle) [e.g. vIsMatch = (oOpt != nil)] [e.g. vKey = oOpt!] [also: vKey = oArray.firstIndex(of:vNeedle) ?? -1] UFL: Array.LastIndexOf [(note: typically return -1 or 0 if no match)] AutoHotkey: ___ C++: auto vIndex = oVec.rend() - std::find(oVec.rbegin(), oVec.rend(), vNeedle) - 1 [note: returns -1 if no match] C#: vKey = Array.LastIndexOf(oArray, vNeedle) [note: returns -1 if no match] Crystal: vKey = oArray.rindex(vNeedle) || -1 [note: rindex() returns nil if no match] Excel: ___ Excel VBA: ___ Go: ___ Java: vKey = oList.lastIndexOf(vNeedle) [note: returns -1 if no match] JavaScript: vKey = oArray.lastIndexOf(vNeedle) [note: returns -1 if no match] Kotlin: vKey = oArray.lastIndexOf(vNeedle) [note: don't confuse with indexOfLast] [note: returns -1 if no match] PHP: $vKey = array_search($vNeedle, array_reverse($oArray, true)) [note: array_reverse() doesn't modify the array] [note: array_reverse(): preserve_keys set to true] [WARNING: since PHP arrays are associative arrays, -1 is a valid key name, hence boolean false is returned if no match] Python: vKey = max(k for k,v in enumerate(oList) if v==vNeedle) [WARNING: throws if no match, consistent with oList.index()] R: vKey = length(oVec) + 1 - match(vNeedle, rev(oVec)) [note: 1-based] [note: returns NA if no match] [also (returns 0 if no match): vKey = length(oVec) + 1 - match(vNeedle, rev(oVec), nomatch=length(oVec)+1)] [also (returns NA if no match): tail(c(NA, which(oVec %in% vNeedle)), 1)] Ruby: vKey = oArray.rindex(vNeedle) || -1 [note: rindex() returns nil if no match] Rust: oOpt = oArray.iter().rposition(|&v| v==vNeedle) [e.g. vIsMatch = oOpt.is_some()] [e.g. vValue = oOpt.unwrap_or(vDefault)] [e.g. vValue = oOpt.unwrap()] [also: vKey: i32 = oArray.iter().rposition(|&v| v==vNeedle).map_or(-1, |v| v as i32)] [note: also works with vectors] Scala: vKey = oArray.lastIndexOf(vNeedle) [note: returns -1 if no match] [note: also works with lists] [FIXME] SQL (MySQL): SELECT max(k) FROM MyTable WHERE v=MyNeedle [FIXME] SQL (PostgreSQL): SELECT max(k) FROM MyTable WHERE v=MyNeedle [also: max(k) FROM unnest(MyArray) WITH ORDINALITY AS t(v, k) WHERE v=MyNeedle] SQL (SQLite): SELECT max(k) FROM MyTable WHERE v==MyNeedle Swift: oOpt = oArray.lastIndex(of:vNeedle) [e.g. vIsMatch = (oOpt != nil)] [e.g. vKey = oOpt!] [also: vKey = oArray.lastIndex(of:vNeedle) ?? -1] UFL: Array.FindIndex [or Array.IndexOfFirst][like Find but returns the index, not the value][like IndexOf but takes a predicate function, not a value][see also: Array.IndexOf/Array.Find] AutoHotkey: ___ C++: auto oIter = std::find_if(std::begin(oArray), std::end(oArray), oFunc) [afterwards: vIsMatch = (oIter != std::end(oArray))] [afterwards: vKey = vIsMatch ? oIter-oArray : -1] [requires (find_if): #include <algorithm>] [also: std::ranges::find_if()] [also (vector): auto oIter = std::find_if(oVec.begin(), oVec.end(), oFunc)] [afterwards (vector): vIsMatch = (oIter != oVec.end())] [afterwards (vector): vKey = vIsMatch ? oIter-oVec.begin() : -1] C#: vKey = oArray.ToList().FindIndex(v=>oFunc(v)) [also: vKey = oArray.ToList().FindIndex(oFunc)] [also: vKey = Array.FindIndex(oArray, oFunc)] [requires (ToList): using System.Linq] [note: returns -1 if no match] Crystal: vKey = oArray.index{|v| oFunc.call(v)} || -1 [note: index() returns nil if no match] [also (throws if no match): oArray.index!{|v| oFunc.call(v)}] [also: rindex/rindex!] Excel: ___ Excel VBA: ___ Go: vKey := slices.IndexFunc(oArray, oFunc) [note: returns -1 if no match] Java: ___ [can use: oOpt = IntStream.range(0, oArray.length).boxed().filter(i->oFunc.test(oArray[i])).findFirst()] [e.g. vIsMatch = oOpt.isPresent()] [e.g. vKey = oOpt.orElse(-1)] [e.g. vKey = oOpt.orElseThrow()] [requires (IntStream): import java.util.stream.*] JavaScript: vKey = oArray.findIndex(v=>oFunc(v)) [also: vKey = oArray.findIndex(oFunc)] [note: returns -1 if no match] [also: findLastIndex] Kotlin: vKey = oArray.indexOfFirst{oFunc(it)} [also: vKey = oArray.indexOfFirst(oFunc)] [note: returns -1 if no match] [also: indexOfLast] [note: don't confuse with lastIndexOf] PHP: $vKey = array_find_key($oArray, fn($v,$k)=>$oFunc($v)) [also: $vKey = key(array_filter($oArray, fn($v)=>$oFunc($v)))] [note (both): returns null if no match] Python: vKey = next((k for k,v in enumerate(oList) if oFunc(v)), -1) R: vKey = Position(\(v) oFunc(v), oVec) [also: vKey = Position(oFunc, oVec)] [note: 1-based] [note: returns NA if no match] [also (returns 0 if no match): vKey = Position(oFunc, oVec, nomatch=0)] [also: can set 'right=TRUE' to search right-to-left] Ruby: vKey = oArray.index{|v| oFunc.call(v)} || -1 [note: index() returns nil if no match] [also: rindex] Rust: oOpt = oArray.iter().position(|&v| oFunc(v)) [e.g. vIsMatch = oOpt.is_some()] [e.g. vKey = oOpt.unwrap_or(vDefault)] [e.g. vKey = oOpt.map_or(-1, |v| v as i32)] [e.g. vKey = oOpt.unwrap()] Scala: vKey = oArray.indexWhere(oFunc(_)) [also: vKey = oArray.indexWhere(oFunc)] [note: returns -1 if no match] [note: also works with lists] SQL (MySQL): ___ [e.g. SELECT min(k) FROM MyTable WHERE v!=''] [note: returns NULL if no match] SQL (PostgreSQL): ___ [e.g. SELECT min(k) FROM MyTable WHERE v!=''] [also: SELECT min(k) FROM unnest(MyArray) WITH ORDINALITY AS t(v, k) WHERE v!=''] [note (both): returns NULL if no match] SQL (SQLite): ___ [e.g. SELECT min(k) FROM MyTable WHERE v!=''] [note: returns NULL if no match] Swift: oOpt = oArray.firstIndex(where:{oFunc($0)}) [also: oOpt = oArray.firstIndex(where:oFunc)] [e.g. vIsMatch = (oOpt != nil)] [e.g. vKey = oOpt!] [also: vKey = oArray.firstIndex(where:{oFunc($0)}) ?? -1] UFL: Array.Find [or Array.FirstMatch][get value of first item that matches predicate][workaround: use a filter and return the first value][see also: Array.Filter/OpNullCoalescing/Array.IndexOf/Array.FindIndex] AutoHotkey: ___ C++: auto oIter = std::find_if(std::begin(oArray), std::end(oArray), oFunc) [afterwards: vIsMatch = (oIter != std::end(oArray))] [afterwards: vValue = *oIter] [requires (find_if): #include <algorithm>] [also: std::ranges::find_if()] [also (vector): auto oIter = std::find_if(oVec.begin(), oVec.end(), oFunc)] [afterwards (vector): vIsMatch = (oIter != oVec.end())] C#: vValue = oArray.ToList().Find(v=>oFunc(v)) [also: vValue = oArray.ToList().Find(oFunc)] [also: vValue = Array.Find(oArray, oFunc)] [WARNING: Find() returns the array's/list's default value if no match (e.g. 0 for ints, null for strings)] [requires (ToList): using System.Linq] Crystal: vValue = oArray.find{|v| oFunc.call(v)} [also: vValue = oArray.find(&oFunc)] [note: returns nil if no match] Excel: ___ Excel VBA: ___ Go: ___ Java: oOpt = Arrays.stream(oArray).filter(v->oFunc.test(v)).findFirst() [also: oOpt = Arrays.stream(oArray).filter(oFunc).findFirst()] [e.g. vIsMatch = oOpt.isPresent()] [e.g. vValue = oOpt.orElseThrow()] JavaScript: vValue = oArray.find(v=>oFunc(v)) [also: vValue = oArray.find(oFunc)] [note: returns undefined if no match] [also: findLast] Kotlin: oOpt = oArray.find{oFunc(it)} [also: oOpt = oArray.find(oFunc)] [e.g. vIsMatch = (oOpt != null)] [e.g. vValue = oOpt!!] PHP: $vValue = array_find($oArray, fn($v,$k)=>$oFunc($v)) [note: returns null if no match] [also: $vValue = current(array_filter($oArray, fn($v)=>$oFunc($v)))] [WARNING ('current' approach): returns false if no match] Python: vValue = next(v for v in oList if oFunc(v)) [also: vValue = next((v for v in oList if oFunc(v)), vDefault)] [note: if no default specified, throws if no match] [note: if specify a default, additional parentheses required, else error: 'Generator expression must be parenthesized'] R: vValue = oVec[oFunc(oVec)][1] [note: 1-based] [e.g. vValue = oVec[oVec==vNeedle][1]] [note: returns NA if no match] [also: vValue = Find(oFunc, oVec, nomatch=vDefault)] Ruby: vValue = oArray.find{|v| oFunc.call(v)} [also: vValue = oArray.find(&oFunc)] [note: returns nil if no match] Rust: oOpt = oArray.into_iter().find(|v| oFunc(*v)) [e.g. vIsMatch = oOpt.is_some()] [e.g. vValue = oOpt.unwrap_or(vDefault)] [e.g. vValue = oOpt.unwrap()] Scala: oOpt = oArray.find(oFunc) [e.g. vIsMatch = oOpt.isDefined] [e.g. vValue = oOpt.get] SQL (MySQL): ___ [e.g. SELECT (SELECT v FROM MyTable WHERE v!='' ORDER BY k LIMIT 1)] [note: returns NULL if no match] SQL (PostgreSQL): ___ [e.g. SELECT (SELECT v FROM MyTable WHERE v!='' ORDER BY k LIMIT 1)] [also: SELECT (SELECT v FROM unnest(MyArray) WITH ORDINALITY AS t(v, k) WHERE v!='' ORDER BY k LIMIT 1)] [note (both): returns NULL if no match] SQL (SQLite): ___ [e.g. SELECT (SELECT v FROM MyTable WHERE v!='' ORDER BY k LIMIT 1)] [note: returns NULL if no match] Swift: oOpt = oArray.first{oFunc($0)} [also: oOpt = oArray.first(where:oFunc)] [e.g. vIsMatch = (oOpt != nil)] [e.g. vValue = oOpt!] UFL: (Array.FindOrDefaultDemo) [or Array.OrInt][for int arrays, get value of first item that doesn't equal zero, else default value][see also: OpOr/OpShortTern] AutoHotkey: ___ C++: auto oIter = std::find_if(std::begin(oArray), std::end(oArray), [](int v) {return v!=0;}) [afterwards: vValue = (oIter != std::end(oArray)) ? *oIter : vDefault] [also (vector): auto oIter = std::find_if(oVec.begin(), oVec.end(), [](int v) {return v!=0;})] [afterwards (vector): vValue = (oIter != oVec.end()) ? *oIter : vDefault] [requires (find_if): #include <algorithm>] C#: vValue = oArray.ToList().Find(v=>v!=0) [also: vValue = Array.Find(oArray, v=>v!=0)] [WARNING: Find() returns the array's/list's default value if no match (e.g. 0 for ints, null for strings)] [requires (ToList): using System.Linq] Crystal: vValue = oArray.find(vDefault){|v| v!=0} Excel: ___ Excel VBA: ___ Go: ___ Java: vValue = Arrays.stream(oArray).filter(v->v!=0).findFirst().orElse(vDefault) JavaScript: vValue = oArray.find(v=>v!=0) ?? vDefault Kotlin: vValue = oArray.find{it!=0} ?: vDefault [WARNING: in Kotlin, '?:' is a null-coalescing operator, not a short-ternary operator: e.g. '0 ?: 123' returns 0, since 0 is non-null] PHP: $vValue = current(array_filter($oArray, fn($v)=>$v!=0)) ?: $vDefault Python: vValue = next((v for v in oList if oFunc(v)), vDefault) R: vValue = Find(\(v) v!=0, oVec, nomatch=vDefault) Ruby: vValue = oArray.find(->{vDefault}){|v| v!=0} Rust: vValue = oArray.into_iter().find(|v| *v!=0).unwrap_or(vDefault) Scala: vValue = oArray.find(_!=0).getOrElse(vDefault) SQL (MySQL): SELECT coalesce((SELECT v FROM MyTable WHERE v!=0 ORDER BY k LIMIT 1), MyDefault) SQL (PostgreSQL): SELECT coalesce((SELECT v FROM MyTable WHERE v!=0 ORDER BY k LIMIT 1), MyDefault) SQL (SQLite): SELECT coalesce((SELECT v FROM MyTable WHERE v!=0 ORDER BY k LIMIT 1), MyDefault) Swift: vValue = oArray.first{$0 != 0} ?? vDefault UFL: Array.Get [or Array.GetKeyValue][key get value] AutoHotkey: vValue := oArray[vKey] [note: 1-based] [note: out of bounds: throws] C++: vValue = oArray[vKey] [also: vValue = oVec.at(vKey)] [also: vValue = oVec[vKey]] [WARNING: oArray[vKey]: if key is out of bounds, it will attempt to read the value anyway] [note: at() throws if key doesn't exist] [WARNING: oVec[vKey]: if key is out of bounds, the behaviour is undefined] C#: vValue = oArray[vKey] [also: oArray.GetValue(vKey)] [note: out of bounds: throws] [also: vValue = oList[vKey]] Crystal: vValue = oArray[vKey] [note: out of bounds: throws] [also (out of bounds: returns nil): vValue = oArray[vKey]?] Excel: ___ Excel VBA: vValue = oArray(vKey) [note: out of bounds: throws] [note: arrays are 0-based unless a different start index specified] Go: vValue := oArray[vKey] [note: out of bounds: throws] Java: vValue = oArray[vKey] [also: vValue = oList.get(vKey)] [note: out of bounds: throws] JavaScript: vValue = oArray[vKey] [also (negative indexes relative to end): vValue = oArray.at(vKey)] [note: out of bounds: returns undefined] Kotlin: vValue = oArray[vKey] [also: vValue = oArray.get(vKey)] [note: out of bounds: oArray[] and oArray.get() throw] PHP: $vValue = $oArray[$vKey] [note: out of bounds: throws] Python: vValue = oList[vKey] [note: out of bounds: throws] R: vValue = oVec[vKey] [note: 1-based] [note: out of bounds: returns NA] [also: vValue = oList[[vKey]]] [note: double square brackets: see R documentation: 'R has three basic indexing operators'] Ruby: vValue = oArray[vKey] [note: out of bounds: returns nil] Rust: vValue = oArray[vKey] [note: out of bounds: throws] [also: vValue = oVec[vKey]] [WARNING (array/vector): get() returns a wrapped value] Scala: vValue = oArray(vKey) [also: vValue = oList(vKey)] [note: out of bounds: throws] SQL (MySQL): SELECT v FROM MyTable WHERE k=MyKey SQL (PostgreSQL): SELECT v FROM MyTable WHERE k=MyKey [also: (MyArray)[MyKey]] SQL (SQLite): SELECT v FROM MyTable WHERE k==MyKey Swift: vValue = oArray[vKey] [note: out of bounds: throws] UFL: Array.GetOrDefault [if key non-existent/null/beyond length, provide default (deviations from this are noted)][see also: StrSplitNthOrDefault/Map.GetOrDefault/Array.PrintWithIndex/OpNullCoalescing] AutoHotkey: vValue := oArray.Get(vKey, vDefault) [WARNING: throws if key beyond length] C++: ___ C#: ___ [can use: oArray.ElementAtOrDefault(vKey)] [WARNING (ElementAtOrDefault): returns null if value is null] [note (ElementAtOrDefault): returns default if key beyond length] [note (ElementAtOrDefault): can't specify a default, the defaults for int/double/string are 0/0/null respectively] [also: oArray[vKey] ?? vDefault] [WARNING: oArray[vKey] throws if key beyond length] Crystal: vValue = oArray.fetch(vKey, vDefault) [also: vValue = oArray.fetch(vKey){|k| oFunc.call(k)}] [note: returns default if key beyond length] [also (throws if key beyond length, MAJOR WARNING: 0/"" treated as truthy): oArray[vKey] || vDefault] Excel: ___ Excel VBA: ___ Go: ___ Java: vValue = Optional.ofNullable(oArray[vKey]).orElse(vDefault) [WARNING: throws if key beyond length] [requires (Optional): import java.util.*] JavaScript: vValue = oArray[vKey] ?? vDefault [note: returns default if value is null/undefined] [note: returns default if key beyond length] Kotlin: vValue = oArray.getOrElse(vKey, oFunc) [e.g. oArray.getOrElse(vKey){vDefault}] [e.g. oArray.getOrElse(vKey, {vDefault})] [WARNING (unlike maps): returns null if value is null] [note (getOrElse): returns default if key beyond length] [also: oArray[vKey] ?: vDefault] [WARNING: oArray[vKey] throws if key beyond length] PHP: $vValue = $oArray[$vKey] ?? $vDefault Python: ___ [can use: vValue = (oList[vKey:vKey+1]or[vDefault])[0]] [also: (oList[vKey:vKey+1]+[vDefault])[0]] [WARNING (both): returns None if value is None] R: ___ [can use: vValue = na.omit(c(oVec[vKey], vDefault))[1]] [note: 1-based] Ruby: vValue = oArray.fetch(vKey, vDefault) [also: vValue = oArray.fetch(vKey){|k| oFunc.call(k)}] [note: returns default if key beyond length] [also (doesn't throw if key beyond length, MAJOR WARNING: 0/"" treated as truthy): oArray[vKey] || vDefault] Rust: ___ [can use (for array/vector of options): oArray[vKey].unwrap_or(vDefault)] Scala: vValue = Option(oArray(vKey)).getOrElse(vDefault) [WARNING: throws if key beyond length] [also: vValue = oArray.zipWithIndex.find(e=>e._2==vKey).getOrElse((vDefault, 0))._1] SQL (MySQL): ___ [e.g. SELECT coalesce((SELECT v FROM MyTable WHERE k=MyKey AND v IS NOT NULL), MyDefault)] SQL (PostgreSQL): ___ [e.g. SELECT coalesce((SELECT v FROM MyTable WHERE k=MyKey AND v IS NOT NULL), MyDefault)] SQL (SQLite): ___ [e.g. SELECT coalesce((SELECT v FROM MyTable WHERE k==MyKey AND v IS NOT NULL), MyDefault)] Swift: vValue = oArray[vKey] ?? vDefault [WARNING: throws if key beyond length] [also: vValue = oArray.enumerated().first{$0.offset==vKey}.map{$1} ?? vDefault] UFL: Array.Set [key set value][see also: Array.InsertAt] AutoHotkey: oArray[vKey] := vValue C++: oArray[vKey] = vValue [also: oVec[vKey] = vValue] C#: oArray[vKey] = vValue [also: oArray.SetValue()] Crystal: oArray[vKey] = vValue Excel: ___ Excel VBA: oArray(vKey) = vValue Go: oArray[vKey] = vValue [note: error if use ':='] Java: oArray[vKey] = vValue [also: oList.set(vKey, vValue)] JavaScript: oArray[vKey] = vValue [also: (create a new array, negative indexes relative to end): oArrayNew = oArray.with(vKey, vValue)] Kotlin: oArray[vKey] = vValue [also: oArray.set(vKey, vValue)] PHP: $oArray[$vKey] = $vValue Python: oList[vKey] = vValue R: oVec[vKey] = vValue Ruby: oArray[vKey] = vValue Rust: oArray[vKey] = vValue Scala: oArray(vKey) = vValue [also: oList = oList.updated(vKey, vValue)] SQL (MySQL): UPDATE MyTable SET v=MyValue WHERE k=MyKey [also (update all rows): UPDATE MyTable SET v=(CASE WHEN k=MyKey THEN MyValue ELSE v END)] SQL (PostgreSQL): UPDATE MyTable SET v=MyValue WHERE k=MyKey [also (update all rows): UPDATE MyTable SET v=(CASE WHEN k=MyKey THEN MyValue ELSE v END)] [also (note: the value may need casting): (MyArray)[:MyKey-1] || MyValue || (MyArray)[MyKey+1:]] [note: 1-based] SQL (SQLite): UPDATE MyTable SET v=MyValue WHERE k==MyKey [also (update all rows): UPDATE MyTable SET v=(CASE WHEN k==MyKey THEN MyValue ELSE v END)] Swift: oArray[vKey] = vValue UFL: (Array.Fill) [or Array.SetAll][set all keys to the same value][see also: Array.Rept] AutoHotkey: ___ C++: std::fill(std::begin(oArray), std::end(oArray), vValue) [also (vector): std::fill(oVec.begin(), oVec.end(), vValue)] C#: Array.Fill(oArray, vValue) Crystal: oArray.fill(vValue) Excel: ___ Excel VBA: ___ Go: ___ Java: java.util.Arrays.fill(oArray, vValue) [also: java.util.Arrays.setAll(oArray, v->vValue)] JavaScript: oArray.fill(vValue) Kotlin: oArray.fill(vValue) PHP: ___ [can use: $oArray = array_fill_keys(array_keys($oArray), $vValue)] [also: $oArray = array_fill(0, count($oArray), $vValue)] Python: ___ [can use: oList[:] = [vValue for _ in oList]] [also: oList = [vValue] * len(oList)] [also: oList = [vValue for _ in oList]] R: oVec[] = vValue Ruby: oArray.fill(vValue) Rust: oArray.fill(vValue) [also: oVec.fill(vValue)] Scala: ___ [can use: oArray = Array.fill(oArray.length)(vValue)] SQL (MySQL): UPDATE MyTable SET v=MyValue [e.g. set the first n keys to the same value: UPDATE MyTable SET v=MyValue WHERE k<=MyCount] SQL (PostgreSQL): UPDATE MyTable SET v=MyValue [e.g. set the first n keys to the same value: UPDATE MyTable SET v=MyValue WHERE k<=MyCount] [also: array_fill(MyValue, ARRAY[cardinality(MyArray)])] SQL (SQLite): UPDATE MyTable SET v=MyValue [e.g. set the first n keys to the same value: UPDATE MyTable SET v=MyValue WHERE k<=MyCount] Swift: ___ [can use: oArray = Array(repeating:vValue, count:oArray.count)] UFL: Array.Swap [swap 2 array items][note: modifies the array] AutoHotkey: ___ C++: std::swap(oArray[vKey1], oArray[vKey2]) [also: std::iter_swap(oVec.begin()+vKey1, oVec.begin()+vKey2)] [requires (iter_swap): #include <algorithm>] C#: (oArray[vKey1], oArray[vKey2]) = (oArray[vKey2], oArray[vKey1]) [note: destructuring assignment] Crystal: oArray.swap(vKey1, vKey2) [also (destructuring assignment): oArray[vKey1], oArray[vKey2] = oArray[vKey2], oArray[vKey1]] Excel: ___ Excel VBA: ___ Go: oArray[vKey1], oArray[vKey2] = oArray[vKey2], oArray[vKey1] [note: destructuring assignment] Java: ___ JavaScript: ___ Kotlin: ___ PHP: [$oArray[$vKey1], $oArray[$vKey2]] = [$oArray[$vKey2], $oArray[$vKey1]] [note: destructuring assignment] Python: oList[vKey1], oList[vKey2] = oList[vKey2], oList[vKey1] [note: destructuring assignment] R: ___ Ruby: oArray[vKey1], oArray[vKey2] = oArray[vKey2], oArray[vKey1] [note: destructuring assignment] Rust: oArray.swap(vKey1, vKey2) [also: oVec.swap(vKey1, vKey2)] Scala: ___ [can use: oArray = oArray.updated(vKey1, oArray(vKey2)).updated(vKey2, oArray(vKey1))] SQL (MySQL): UPDATE MyTable SET k=if(k=MyKey1,MyKey2,MyKey1) WHERE k IN (MyKey1,MyKey2) [also: UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 ELSE MyKey1 END) WHERE k IN (MyKey1,MyKey2)] [also (update all rows): UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 WHEN k=MyKey2 THEN MyKey1 ELSE k END)] SQL (PostgreSQL): UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 ELSE MyKey1 END) WHERE k IN (MyKey1,MyKey2) [also (update all rows): UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 WHEN k=MyKey2 THEN MyKey1 ELSE k END)] SQL (SQLite): UPDATE MyTable SET k=iif(k==MyKey1,MyKey2,MyKey1) WHERE k IN (MyKey1,MyKey2) [also: UPDATE MyTable SET k=(CASE WHEN k==MyKey1 THEN MyKey2 ELSE MyKey1 END) WHERE k IN (MyKey1,MyKey2)] [also (update all rows): UPDATE MyTable SET k=(CASE WHEN k==MyKey1 THEN MyKey2 WHEN k==MyKey2 THEN MyKey1 ELSE k END)] Swift: oArray.swapAt(vKey1, vKey2) [also (destructuring assignment): (oArray[vKey1], oArray[vKey2]) = (oArray[vKey2], oArray[vKey1])] [note: swap() fails with 'overlapping accesses' error: swap(&oArray[vKey1], &oArray[vKey2])] UFL: Array.Swapped [swap 2 array items][note: doesn't modify the array (creates a new array)] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [can use: oArrayNew = oArray.updated(vKey1, oArray(vKey2)).updated(vKey2, oArray(vKey1))] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Array.Push [or Array.Append][append one value] AutoHotkey: oArray.Push(vValue) C++: oVec.push_back(vValue) C#: var oArrayNew = oArray.Append(vValue).ToArray() [requires (Append/Concat/ToList): using System.Linq] [also: var oArray = oArray.Concat(new[]{vValue}).ToArray()] [also: Array.Resize(ref oArray, oArray.Length+1); oArray[oArray.GetUpperBound(0)] = vValue] [also: var oList = oArray.ToList(); oList.Add(vValue); var oArrayNew = oList.ToArray();] Crystal: oArray.push(vValue) [also: oArray << vValue] Excel: ___ Excel VBA: ReDim Preserve oArray(UBound(oArray) + 1) [afterwards: oArray(UBound(oArray)) = vValue] Go: oSlice = append(oSlice, vValue) Java: oList.add(vValue) JavaScript: oArray.push(vValue) Kotlin: oArray.add(vValue) PHP: array_push($oArray, $vValue) [note: it finds the maximum (non-negative) integer key n, and creates key n+1, else creates key 0] Python: oList.append(vValue) R: oVec = c(oVec, vValue) [also: oList[[length(oList)+1]] = vValue] [also: oList[[length(oList)+1]] = oVec] [also: oVec = append(oVec, vValue)] [also: oList = c(oList, vValue)] [also: oList = append(oList, vValue)] [also: oList = c(oList, list(oVec))] [also: oList = append(oList, list(oVec))] [WARNING: 'c(oList, oVec)' and 'append(oList, oVec)' append elements, not the vector as one item] Ruby: oArray.push(vValue) [also: oArray << vValue] Rust: oVec.push(vValue) Scala: oArray :+= vValue [also: oArrayNew = oArray :+ vValue] [note (both): also works with lists] SQL (MySQL): SET @vMax = (SELECT max(k) FROM MyTable); INSERT INTO MyTable (k,v) VALUES (@vMax+1, MyValue); [also (if column k is auto-generated): INSERT INTO MyTable (v) VALUES (MyValue)] [also (if column k is auto-generated, push the default value): INSERT INTO MyTable () VALUES ()] SQL (PostgreSQL): INSERT INTO MyTable VALUES ((SELECT max(k) FROM MyTable)+1, MyValue) [also (if column k is auto-generated): INSERT INTO MyTable (v) VALUES (MyValue)] [also (if column k is auto-generated, push the default value): INSERT INTO MyTable DEFAULT VALUES] [also: MyArray || MyValue] [also: array_append(MyArray, MyValue)] SQL (SQLite): INSERT INTO MyTable VALUES ((SELECT max(k) FROM MyTable)+1, MyValue) [also (if column k is auto-generated): INSERT INTO MyTable (v) VALUES (MyValue)] [also (if column k is auto-generated, push the default value): INSERT INTO MyTable DEFAULT VALUES] Swift: oArray.append(vValue) UFL: Array.PushMult [or Array.PushArray/Array.AppendMult][append multiple values][append suffix values][modify an array by appending (the values of) another array to it (concatenate arrays)] AutoHotkey: oArray.Push(oArraySfx*) [note: the suffix array can be empty] C++: oVec.insert(oVec.end(), oVecSfx.begin(), oVecSfx.end()) [can use (to create a new array): auto* oArrayNew = new std::string[vSize+vSizeSfx]] [can use (to copy elements): std::copy()] [requires (copy): #include <algorithm>] C#: var oArrayNew = oArray.Concat(oArraySfx).ToArray() [requires (Concat/ToList): using System.Linq] [also: var oList = oArray.ToList(); oList.AddRange(oArraySfx); var oArrayNew = oList.ToArray();] [also: CopyTo()] [also: Resize() and Copy()] Crystal: oArray.concat(oArraySfx) [also: oArray += oArraySfx] Excel: ___ Excel VBA: ___ Go: oSlice = append(oSlice, oSliceSfx...) Java: oList.addAll(oListSfx) [also (concatenate via arraycopy): System.arraycopy(oArraySfx, 0, oArrayNew, oArray.length, oArraySfx.length)] [beforehand (concatenate via arraycopy): var oArrayNew = Arrays.copyOf(oArray, oArray.length+oArraySfx.length)] [also (concatenate via streams): String[] oArrayNew = Stream.concat(Arrays.stream(oArray), Arrays.stream(oArraySfx)).toArray(String[]::new)] [requires (concatenate via streams): import java.util.stream.*] JavaScript: oArray.push(...oArraySfx) [also: Array.prototype.push.apply(oArray, oArraySfx)] [also: oArrayNew = oArray.concat(oArraySfx)] [also: oArrayNew = [...oArray, ...oArraySfx]] Kotlin: oArray += oArraySfx PHP: array_push($oArray, ...$oArraySfx) [also: $oArrayNew = array_merge($oArray, $oArraySfx)] Python: oList.extend(oListSfx) R: oVec = c(oVec, oVecSfx) [also: oVec = append(oVec, oVecSfx)] [also (can append lists also): oList = c(oList, oVecSfx)] [also (can append lists also): oList = append(oList, oVecSfx)] Ruby: oArray.push(*oArraySfx) [also: oArray.concat(oArraySfx)] [also: oArray += oArraySfx] Rust: oVec.append(&mut oVecSfx.clone()) [also: oVec.extend(oVecSfx.clone())] [also: oVec.extend(oArraySfx)] Scala: oArray ++= oArraySfx [also: oArrayNew = oArray ++ oArraySfx] [note (both): also works with lists] [note: concat (++= and ++), and appendedAll (:++= and :++)] SQL (MySQL): INSERT INTO MyTable SELECT k+(SELECT COUNT(*) FROM MyTable),v FROM MyTableSfx [also (print combined table): SELECT * FROM MyTable UNION ALL SELECT k+(SELECT COUNT(*) FROM MyTable),v FROM MyTableSfx] SQL (PostgreSQL): INSERT INTO MyTable SELECT k+(SELECT COUNT(*) FROM MyTable),v FROM MyTableSfx [also (print combined table): SELECT * FROM MyTable UNION ALL SELECT k+(SELECT COUNT(*) FROM MyTable),v FROM MyTableSfx] [also: MyArray || MyArraySfx] SQL (SQLite): INSERT INTO MyTable SELECT k+(SELECT COUNT(*) FROM MyTable),v FROM MyTableSfx [also (print combined table): SELECT * FROM MyTable UNION ALL SELECT k+(SELECT COUNT(*) FROM MyTable),v FROM MyTableSfx] Swift: oArray.append(contentsOf:oArraySfx) [also: oArray += oArraySfx] UFL: Array.InsertAt [insert one item (and shift item(s) right)][note: state if 'insert at' doesn't allow pushing (inserting at an index one beyond the last element)][see also: Array.Set] AutoHotkey: oArray.InsertAt(vKey, vValue) C++: oVec.insert(oVec.begin()+vKey, vValue) C#: oList.Insert(vKey, vValue) [e.g. var oList = oArray.ToList(); oList.Insert(vKey, vValue); var oArrayNew = oList.ToArray();] [requires (ToList): using System.Linq] Crystal: oArray.insert(vKey, vValue) Excel: ___ Excel VBA: ___ Go: oSlice = slices.Insert(oSlice, vKey, vValue) Java: oList.add(vKey, vValue) JavaScript: oArray.splice(vKey, 0, vValue) Kotlin: ___ [can use: oArrayNew = oArray.copyOfRange(0, vKey) + vValue + oArray.copyOfRange(vKey, oArray.size)] [also: oArrayNew = oArray.sliceArray(0..<vKey) + vValue + oArray.sliceArray(vKey..<oArray.size)] [also: var oList = oArray.toMutableList(); oList.add(vKey, vValue); var oArrayNew = oList.toTypedArray()] PHP: array_splice($oArray, $vKey, 0, [$vValue]) [note: square brackets unnecessary, 'unless the element is an array itself, an object or null'] Python: oList.insert(vKey, vValue) R: oVec = append(oVec, vValue, after=vKey-1) [note: 1-based] Ruby: oArray.insert(vKey, vValue) Rust: oVec.insert(vKey, vValue) Scala: oArrayNew = oArray.patch(vKey, Array(vValue), 0) [note: also works with lists] [FIXME] SQL (MySQL): UPDATE MyTable SET k=k+1 WHERE k>=MyPos; INSERT INTO MyTable VALUES (MyPos, MyValue); [FIXME] SQL (PostgreSQL): UPDATE MyTable SET k=k+1 WHERE k>=MyPos; INSERT INTO MyTable VALUES (MyPos, MyValue); [also (note: the value may need casting): (MyArray)[:MyKey-1] || MyValue || (MyArray)[MyKey:]] [note: 1-based] SQL (SQLite): UPDATE MyTable SET k=k+1 WHERE k>=MyPos; INSERT INTO MyTable VALUES (MyPos, MyValue); Swift: oArray.insert(vValue, at:vKey) UFL: Array.InsertAtMult [insert item(s) (and shift item(s) right)][insert infix values][see also: Array.Splice] AutoHotkey: oArray.InsertAt(vKey, oArrayIfx*) [note: throws if the infix array is empty] C++: oVec.insert(oVec.begin()+vKey, oVecIfx.begin(), oVecIfx.end()) C#: oList.InsertRange(vKey, oArrayIfx) [e.g. var oList = oArray.ToList(); oList.InsertRange(vKey, oArrayIfx); var oArrayNew = oList.ToArray();] [requires (ToList): using System.Linq] Crystal: oArray.insert_all(vKey, oArrayIfx) [also: oArray[vKey...vKey] = oArrayIfx] [also: oArray = oArray[0...vKey] + oArrayIfx + oArray[vKey..]] Excel: ___ Excel VBA: ___ Go: oSlice = slices.Insert(oSlice, vKey, oSliceIfx...) Java: oList.addAll(vKey, oListIfx) JavaScript: oArray.splice(vKey, 0, ...oArrayIfx) Kotlin: ___ [can use: oArrayNew = oArray.copyOfRange(0, vKey) + oArrayIfx + oArray.copyOfRange(vKey, oArray.size)] [also: oArrayNew = oArray.sliceArray(0..<vKey) + oArrayIfx + oArray.sliceArray(vKey..<oArray.size)] [also: var oList = oArray.toMutableList(); oList.addAll(vKey, oArrayIfx.toList()); var oArrayNew = oList.toTypedArray()] PHP: array_splice($oArray, $vKey, 0, $oArrayIfx) Python: oList[vKey:vKey] = oListIfx [note: slice assignment] R: oVec = append(oVec, oVecIfx, after=vKey-1) [note: 1-based] Ruby: oArray.insert(vKey, *oArrayIfx) Rust: oVec.splice(vKey..vKey, oVecIfx.iter().cloned()) [also: oVec.splice(vKey..vKey, oArrayIfx.iter().cloned())] Scala: oArrayNew = oArray.patch(vKey, oArrayIfx, 0) [note: also works with lists] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ [can use: (MyArray)[:MyKey-1] || MyArrayIfx || (MyArray)[MyKey:]] [note: 1-based] SQL (SQLite): ___ Swift: oArray.insert(contentsOf:oArrayIfx, at:vKey) UFL: Array.Prepend [or Array.InsertAtStart][insert one item at start (and shift item(s) right)] AutoHotkey: oArray.InsertAt(1, vValue) C++: oVec.insert(oVec.begin(), vValue) C#: var oArrayNew = oArray.Prepend(vValue).ToArray() [requires (Concat/Prepend/ToList): using System.Linq] [also: var oArrayNew = new[]{vValue}.Concat(oArray).ToArray()] [also: var oList = oArray.ToList(); oList.Insert(0, vValue); var oArrayNew = oList.ToArray();] Crystal: oArray.unshift(vValue) Excel: ___ Excel VBA: ___ Go: oSlice = slices.Insert(oSlice, 0, vValue) Java: oList.add(0, vValue) JavaScript: oArray.unshift(vValue) Kotlin: ___ [can use: oArrayNew = arrayOf(vValue) + oArray] [also: var oList = oArray.toMutableList(); oList.add(0, vValue); var oArrayNew = oList.toTypedArray()] PHP: array_unshift($oArray, $vValue) Python: oList.insert(0, vValue) R: oVec = c(vValue, oVec) Ruby: oArray.unshift(vValue) Rust: oVec.insert(0, vValue) Scala: oArray +:= vValue [also: oArrayNew = vValue +: oArray] [note (both): also works with lists] [FIXME] SQL (MySQL): UPDATE MyTable SET k=k+1; INSERT INTO MyTable VALUES (1, MyValue); [FIXME] SQL (PostgreSQL): UPDATE MyTable SET k=k+1; INSERT INTO MyTable VALUES (1, MyValue); [also: MyValue || MyArray] [also: array_prepend(MyValue, MyArray)] SQL (SQLite): UPDATE MyTable SET k=k+1; INSERT INTO MyTable VALUES (1, MyValue); Swift: oArray.insert(vValue, at:0) UFL: Array.PrependMult [or Array.InsertAtStartMult][insert item(s) at start (and shift item(s) right)][prepend prefix values] AutoHotkey: oArray.InsertAt(1, oArrayPfx*) [note: throws if the prefix array is empty] C++: oVec.insert(oVec.begin(), oVecPfx.begin(), oVecPfx.end()) C#: var oArrayNew = oArrayPfx.Concat(oArray).ToArray() [requires (Concat/ToList): using System.Linq] [also: var oList = oArray.ToList(); oList.InsertRange(0, oArrayPfx); var oArrayNew = oList.ToArray();] Crystal: oArray[0...0] = oArrayPfx [also: oArray = oArrayPfx + oArray] Excel: ___ Excel VBA: ___ Go: oSlice = slices.Insert(oSlice, 0, oSlicePfx...) Java: oList.addAll(0, oListPfx) JavaScript: oArray.unshift(...oArrayPfx) Kotlin: ___ [can use: oArrayNew = oArrayPfx + oArray] [also: var oList = oArray.toMutableList(); oList.addAll(0, oArrayPfx.toList()); var oArrayNew = oList.toTypedArray()] PHP: array_unshift($oArray, ...$oArrayPfx) Python: oList[:0] = oListPfx [note: slice assignment] R: oVec = c(oVecPfx, oVec) Ruby: oArray.insert(0, *oArrayPfx) Rust: oVec.splice(0..0, oVecPfx.iter().cloned()) [also: oVec.splice(0..0, oArrayPfx.iter().cloned())] Scala: oArray ++:= oArrayPfx [also: oArrayNew = oArrayPfx ++: oArray] [note (both): also works with lists] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ [also: MyArrayPfx || MyArray] SQL (SQLite): ___ Swift: oArray.insert(contentsOf:oArrayPfx, at:0) UFL: Array.Pop [or Array.RemoveLast][remove last value (and typically simultaneously retrieve the last value)][see also: Array.Last] AutoHotkey: vValue := oArray.Pop() C++: oVec.pop_back() [beforehand: vValue = oVec.back()] C#: var oArrayNew = oArray.SkipLast(1).ToArray() [beforehand: vValue = oArray.Last()] [also (beforehand): vValue = oArray[oArray.Length-1]] [requires (SkipLast/Last): using System.Linq] Crystal: vValue = oArray.pop [also: oArray.pop?] Excel: ___ Excel VBA: ReDim Preserve oArray(UBound(oArray) - 1) [beforehand: vValue = oArray(UBound(oArray))] Go: oSlice = oSlice[:len(oSlice)-1] [beforehand: vValue := oSlice[len(oSlice)-1]] Java: oList.remove(oList.size()-1) [beforehand: vValue = oList.get(oList.size()-1)] [also: var oArrayNew = Arrays.copyOfRange(oArray, 0, oArray.length-1)] JavaScript: vValue = oArray.pop() Kotlin: oArrayNew = oArray.dropLast(1).toTypedArray() [beforehand: var vValue = oArray.last()] [also (beforehand): var vValue = oArray[oArray.size-1]] PHP: $vValue = array_pop($oArray) [WARNING: removes the last key to be added (not necessarily an integer key, not necessarily the largest integer key)] [can use (to get the key name): array_key_last($oArray)] Python: vValue = oList.pop() R: oVecNew = head(oVec, -1) [beforehand: vValue = tail(oVec, 1)] [also: oVecNew = oVec[-length(oVec)]] [note: head(oVec, n) copies the first n elements, head(oVec, -n) copies the first length-n elements (all except the last n elements)] [note: oVec[-n] copies everything except element n] Ruby: vValue = oArray.pop Rust: vValue = oVec.pop().unwrap() Scala: oArrayNew = oArray.dropRight(1) [note: also works with lists] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k=(SELECT max(k) FROM MyTable) [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k=(SELECT max(k) FROM MyTable) [also: trim_array(MyArray, 1)] SQL (SQLite): DELETE FROM MyTable WHERE k==(SELECT max(k) FROM MyTable) Swift: vValue = oArray.removeLast() [also: vValue = oArray.popLast()!] [also: oArrayNew = Array(oArray.dropLast())] UFL: Array.PopMult [or Array.RemoveLastMult/Array.DropLastAsArray/Array.DropRightAsArray][remove multiple values][see also: Array.SliceLast] AutoHotkey: oArray.RemoveAt(-vCount, vCount) C++: oVec.resize(oVec.size()-vCount > 0 ? oVec.size()-vCount : 0) C#: oArrayNew = oArray.SkipLast(vCount).ToArray() [requires (SkipLast): using System.Linq] Crystal: oArray.pop(vCount) Excel: ___ Excel VBA: ReDim Preserve oArray(UBound(oArray) - vCount) Go: oSlice = oSlice[:len(oSlice)-vCount] Java: var oArrayNew = Arrays.copyOfRange(oArray, 0, oArray.length-vCount) [WARNING: ArrayList.removeRange() has protected access] JavaScript: oArray.splice(-vCount) Kotlin: oArrayNew = oArray.dropLast(vCount).toTypedArray() PHP: array_splice($oArray, -$vCount) Python: oListNew = oList[:-3] R: oVecNew = head(oVec, -vCount) [note: head(oVec, n) copies the first n elements, head(oVec, -n) copies the first length-n elements (all except the last n elements)] Ruby: oArray.pop(vCount) Rust: oVec.truncate(oVec.len()-vCount) [also: oVec.drain(oVec.len()-vCount..)] [note: can use saturating_sub to subtract and clamp (to get numbers within bounds)] Scala: oArrayNew = oArray.dropRight(vCount) [note: also works with lists] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k>(SELECT max(k) FROM MyTable)-MyCount [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k>(SELECT max(k) FROM MyTable)-MyCount [also: trim_array(MyArray, MyCount)] SQL (SQLite): DELETE FROM MyTable WHERE k>(SELECT max(k) FROM MyTable)-MyCount Swift: oArray.removeLast(vCount) [also: oArrayNew = Array(oArray.dropLast(vCount))] UFL: Array.RemoveAt [remove one item (and shift item(s) left)][WARNING: the return value often differs depending on the language, e.g. removed value/removed values array/modified array][see also: Array.RemoveFirst/Array.Pop] AutoHotkey: vValue := oArray.RemoveAt(vKey) C++: oIter = oVec.erase(oVec.begin()+vKey) [beforehand: vValue = oVec.at(vKey)] C#: oList.RemoveAt(vKey) [note: no return value] [e.g. var oList = oArray.ToList(); oList.RemoveAt(vKey); var oArrayNew = oList.ToArray();] [beforehand: vValue = oList[vKey]] [requires (ToList): using System.Linq] Crystal: vValue = oArray.delete_at(vKey) Excel: ___ Excel VBA: ___ Go: oSlice = slices.Delete(oSlice, vKey, vKey+1) [beforehand: vValue := oSlice[vKey]] Java: vValue = oList.remove(vKey) JavaScript: oValues = oArray.splice(vKey, 1) Kotlin: ___ [can use: oArrayNew = oArray.copyOfRange(0, vKey) + oArray.copyOfRange(vKey+1, oArray.size)] [also: oArrayNew = oArray.sliceArray(0..<vKey) + oArray.sliceArray(vKey+1..<oArray.size)] [also: var oList = oArray.toMutableList(); var vValue = oList.removeAt(vKey); var oArrayNew = oList.toTypedArray()] [also: oArrayNew = (oArray.toList().subList(0, vKey) + oArray.toList().subList(vKey+1, oArray.size)).toTypedArray()] PHP: $oValues = array_splice($oArray, $vKey, 1) Python: vValue = oList.pop(vKey) [WARNING: called 'pop' but can remove from any location] R: oVecNew = oVec[-vKey] [beforehand: vValue = oVec[vKey]] Ruby: vValue = oArray.delete_at(vKey) Rust: vValue = oVec.remove(vKey) Scala: oArrayNew = oArray.patch(vKey, oArray.take(0), 1) [beforehand: vValue = oArray(vKey)] [note: also works with lists] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k=MyKey; UPDATE MyTable SET k=k-1 WHERE k>MyKey; [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k=MyKey; UPDATE MyTable SET k=k-1 WHERE k>MyKey; [also: (MyArray)[:MyKey-1] || (MyArray)[MyKey+1:]] [note: 1-based] SQL (SQLite): DELETE FROM MyTable WHERE k==MyKey; UPDATE MyTable SET k=k-1 WHERE k>MyKey; Swift: vValue = oArray.remove(at:vKey) UFL: Array.RemoveAtMult [remove item(s) (and shift item(s) left)][see also: Array.RemoveFirstMult/Array.PopMult/Array.Splice] AutoHotkey: oArray.RemoveAt(vKey, vCount) [WARNING: RemoveAt(vKey) returns 1 value, RemoveAt(vKey, vCount) returns nothing] [deprecated (AHK v1): vCount := oObj.RemoveAt(vKey, vCount)] C++: oVec.erase(oVec.begin()+vKey, oVec.begin()+vKey+vCount) C#: oList.RemoveRange(vKey, vCount) [e.g. var oList = oArray.ToList(); oList.RemoveRange(vKey, vCount); var oArrayNew = oList.ToArray();] [requires (ToList): using System.Linq] Crystal: oArray[vKey...vKey+vCount] = oArray[0...0] [also: oArray[vKey...vKey+vCount] = [] of Int32] [also: oArray = oArray.each_with_index.reject{|v,k| (vKey...vKey+vCount).includes?(k)}.map{|v|v[0]}.to_a] Excel: ___ Excel VBA: ___ Go: oSlice = slices.Delete(oSlice, vKey, vKey+vCount) Java: ___ [WARNING: ArrayList.removeRange() has protected access] JavaScript: oArray.splice(vKey, vCount) Kotlin: ___ [can use: oArrayNew = oArray.copyOfRange(0, vKey) + oArray.copyOfRange(vKey+vCount, oArray.size)] [also: oArrayNew = oArray.sliceArray(0..<vKey) + oArray.sliceArray(vKey+vCount..<oArray.size)] [also (keep values *not* in range): oArrayNew = oArray.filterIndexed{k,_->!(vKey..<(vKey+vCount)).contains(k)}.toTypedArray()] [also: oArrayNew = (oArray.toList().subList(0, vKey) + oArray.toList().subList(vKey+vCount, oArray.size)).toTypedArray()] PHP: array_splice($oArray, $vKey, $vCount) Python: del oList[vKey:vKey+vCount] R: oVecNew = oVec[-(vKey:(vKey+vCount-1))] Ruby: oArray[vKey...vKey+vCount] = [] [also: oArray = oArray.reject.with_index{|v,k| (vKey...vKey+vCount).include?k}] Rust: oVec.drain(vKey..vKey+vCount) Scala: oArrayNew = oArray.patch(vKey, oArray.take(0), vCountDel) [note: also works with lists] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k BETWEEN MyKey AND MyKey+MyCount-1; UPDATE MyTable SET k=k-MyCount WHERE k>MyKey; [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k BETWEEN MyKey AND MyKey+MyCount-1; UPDATE MyTable SET k=k-MyCount WHERE k>MyKey; [also: (MyArray)[:MyKey-1] || (MyArray)[MyKey+MyCount:]] [note: 1-based] SQL (SQLite): DELETE FROM MyTable WHERE k BETWEEN MyKey AND MyKey+MyCount-1; UPDATE MyTable SET k=k-MyCount WHERE k>MyKey; Swift: oArray.removeSubrange(vKey..<vKey+vCount) UFL: Array.RemoveAtRest [remove item(s) from key onwards (remove key n and subsequent items)][note: essentially equivalent to Array.SliceFirst with vCount=vKeyZeroBased or vCount=vKeyOneBased-1][note: Key/Count beyond array could throw][see also: Array.Splice/Array.Filter/Array.SliceRest] AutoHotkey: oArray.RemoveAt(vKey, oArray.Length-vKey+1) [note: returns nothing] C++: oVec.erase(oVec.begin()+vKey, oVec.end()) C#: oList.RemoveRange(vKey, oList.Length-vKey) [e.g. var oList = oArray.ToList(); oList.RemoveRange(vKey, oList.Length-vKey); var oArrayNew = oList.ToArray();] [requires (ToList): using System.Linq] Crystal: oArray[vKey..] = oArray[0...0] [also: oArray[vKey..] = [] of Int32] [also: oArray = oArray.each_with_index.reject{|v,k| (vKey..).includes?(k)}.map{|v|v[0]}.to_a] Excel: ___ Excel VBA: ___ Go: ___ [can use: oSliceNew := oSlice[:vKey]] [can use: oSlice = oSlice[:vKey]] Java: ___ [WARNING: ArrayList.removeRange() has protected access] JavaScript: oArray.splice(vKey) Kotlin: ___ [can use: oArrayNew = oArray.copyOfRange(0, vKey)] [also: oArrayNew = oArray.sliceArray(0..<vKey)] [also (keep values in range): oArrayNew = oArray.filterIndexed{k,_->(0..<vKey).contains(k)}.toTypedArray()] [also: oArrayNew = oArray.toList().subList(0, vKey).toTypedArray()] PHP: array_splice($oArray, $vKey) Python: del oList[vKey:] R: oVecNew = oVec[-(vKey:(length(oVec)+1))] [note: using '+1' avoids removing the last key when vKey > length(oVec)] [note: equivalent: 'oVec[-(a:b)]' and 'oVec[-(b:a)]'] Ruby: oArray[vKey..] = [] [also: oArray = oArray.reject.with_index{|v,k| (vKey..).include?k}] Rust: oVec.drain(vKey..) Scala: oArrayNew = oArray.patch(vKey, oArray.take(0), oArray.length) [note: works even if the count, e.g. oArray.length, goes beyond the end of the array] [note: also works with lists] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k >= MyKey; [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k >= MyKey; [also: (MyArray)[:MyKey-1]] SQL (SQLite): DELETE FROM MyTable WHERE k >= MyKey; Swift: oArray.removeSubrange(vKey...) [note: throws if use '..'] UFL: Array.RemoveFirst [remove first item/element] AutoHotkey: oArray.RemoveAt(1) C++: oVec.erase(oVec.begin()) C#: var oArrayNew = oArray.Skip(1).ToArray() [requires (Skip): using System.Linq] Crystal: oArray.shift [also: oArray.shift?] Excel: ___ Excel VBA: ___ Go: oSlice = slices.Delete(oSlice, 0, 1) Java: oList.remove(0) [also: var oArrayNew = Arrays.copyOfRange(oArray, 1, oArray.length)] JavaScript: oArray.shift() Kotlin: oArrayNew = oArray.drop(1).toTypedArray() [can use: oList = oArray.toMutableList(), oList.removeFirst(), oArrayNew = oList.toTypedArray()] [can use (instead of removeFirst()): oList.removeAt(0)] PHP: array_shift($oArray) [also: array_splice($oArray, 0, 1)] [WARNING (array_shift/array_splice): removes the first key to be added (not necessarily an integer key, not necessarily the smallest integer key)] [can use (to get the key name): array_key_first($oArray)] Python: oList.pop(0) [WARNING: called 'pop' but can remove from any location] [also: del oList[:1]] [also: oListNew = oList[1:]] R: oVecNew = tail(oVec, -1) [also: oVecNew = oVec[-1]] [note: tail(oVec, n) copies the last n elements, tail(oVec, -n) copies the last length-n elements (all except the first n elements)] [note: oVec[-n] copies everything except element n] Ruby: oArray.shift Rust: oVec.remove(0) Scala: oArrayNew = oArray.drop(1) [also: oArrayNew = oArray.tail] [note (both): also works with lists] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k=1; UPDATE MyTable SET k=k-1; [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k=1; UPDATE MyTable SET k=k-1; [also: (MyArray)[2:]] SQL (SQLite): DELETE FROM MyTable WHERE k==1; UPDATE MyTable SET k=k-1; Swift: oArray.removeFirst() [also: oArrayNew = Array(oArray.dropFirst())] UFL: Array.RemoveFirstMult [or Array.DropAsArray/Array.DropFirstAsArray/Array.DropLeftAsArray][remove the first n elements] AutoHotkey: oArray.RemoveAt(1, vCount) C++: oVec.erase(oVec.begin(), oVec.begin()+vCount) C#: var oArrayNew = oArray.Skip(vCount).ToArray() [requires (Skip): using System.Linq] Crystal: oArray.shift(vCount) Excel: ___ Excel VBA: ___ Go: oSlice = slices.Delete(oSlice, 0, vCount) Java: var oArrayNew = Arrays.copyOfRange(oArray, vCount, oArray.length) [WARNING: ArrayList.removeRange() has protected access] JavaScript: oArray.splice(0, vCount) [also: oArrayNew = oArray.slice(vCount)] [note (both): returns an array] [note: splice() modifies the array, and returns any deleted elements] [note: slice() does not modify the array] Kotlin: oArrayNew = oArray.drop(vCount).toTypedArray() PHP: array_splice($oArray, 0, $vCount) Python: del oList[:vCount] R: oVecNew = tail(oVec, -vCount) [note: tail(oVec, n) copies the last n elements, tail(oVec, -n) copies the last length-n elements (all except the first n elements)] Ruby: oArray.shift(vCount) Rust: oVec.drain(0..vCount) Scala: oArrayNew = oArray.drop(vCount) [note: also works with lists] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k<=MyCount; UPDATE MyTable SET k=k-MyCount; [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k<=MyCount; UPDATE MyTable SET k=k-MyCount; [also: (MyArray)[MyCount+1:]] SQL (SQLite): DELETE FROM MyTable WHERE k<=MyCount; UPDATE MyTable SET k=k-MyCount; Swift: oArray.removeFirst(vCount) [also: oArrayNew = Array(oArray.dropFirst(vCount))] UFL: Array.Splice [or Array.RemoveAndInsert][remove n elements (and shift elements left), and insert 0 or more elements][insert infix values][see also: Array.RemoveAtMult/Array.InsertAtMult] AutoHotkey: ___ C++: ___ C#: ___ Crystal: oArray[vKey...vKey+vCountDel] = oArrayIfx Excel: ___ Excel VBA: ___ Go: oSlice = slices.Replace(oSlice, vKey, vKey+vCountDel, oSliceIfx...) Java: ___ JavaScript: oArray.splice(vKey, vCountDel, ...oArrayIfx) Kotlin: ___ PHP: array_splice($oArray, $vKey, $vCountDel, $oArrayIfx) Python: oList[vKey:vKey+vCountDel] = oListIfx [note: slice assignment] R: ___ [can use: oVec = append(oVec[-(vKey:(vKey+vCountDel-1))], oVecIfx, after=vKey-1)] Ruby: oArray[vKey...vKey+vCountDel] = oArrayIfx Rust: oVec.splice(vKey..vKey+vCountDel, oVecIfx) Scala: oArrayNew = oArray.patch(vKey, oArrayIfx, vCountDel) [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ [can use: (MyArray)[:MyKey-1] || MyArrayIfx || (MyArray)[MyKey+MyCount:]] [note: 1-based] SQL (SQLite): ___ Swift: oArray.replaceSubrange(vKey..<vKey+vCountDel, with:oArrayIfx) UFL: Array.Move [remove element at old index, recalculate indexes, reinsert element at new index][e.g. YouTube API: move playlist item to new index][see also: Array.RemoveAt/Array.InsertAt] AutoHotkey: ___ [can use: vValue := oArray.RemoveAt(vKeyOld)] [afterwards: oArray.InsertAt(vKeyNew, vValue)] C++: ___ [can use: auto vValue = oVec.at(vKeyOld); oVec.erase(oVec.begin()+vKeyOld); oVec.insert(oVec.begin()+vKeyNew, vValue);] C#: ___ [can use: var vValue = oArray[vKeyOld]; var oList = oArray.ToList(); oList.RemoveAt(vKeyOld); oList.Insert(vKeyNew, vValue); oArray = oList.ToArray();] [requires (ToList): using System.Linq] Crystal: ___ [can use: vValue = oArray.delete_at(vKeyOld); oArray.insert(vKeyNew, vValue)] Excel: ___ Excel VBA: ___ Go: ___ [can use: vValue := oSlice[vKeyOld]; oSlice = slices.Delete(oSlice, vKeyOld, vKeyOld+1); oSlice = slices.Insert(oSlice, vKeyNew, vValue)] Java: ___ [can use: var vValue = oList.remove(vKeyOld); oList.add(vKeyNew, vValue);] JavaScript: ___ [can use: vValue = oArray.splice(vKeyOld, 1)[0]; oArray.splice(vKeyNew, 0, vValue);] Kotlin: ___ [can use: var oList = oArray.toMutableList(); var vValue = oList.removeAt(vKeyOld); oList.add(vKeyNew, vValue); oArray = oList.toTypedArray()] PHP: ___ [can use: $oValues = array_splice($oArray, $vKeyOld, 1); array_splice($oArray, $vKeyNew, 0, $oValues);] Python: ___ [can use: vValue = oList.pop(vKeyOld); oList.insert(vKeyNew, vValue)] [WARNING: called 'pop' but can remove from any location] R: ___ [can use: vValue = oVec[vKeyOld]; oVec = oVec[-vKeyOld]; oVec = append(oVec, vValue, after=vKeyNew-1)] [note: 1-based] Ruby: ___ [can use: vValue = oArray.delete_at(vKeyOld); oArray.insert(vKeyNew, vValue)] Rust: ___ [can use: let mut vValue = oVec.remove(vKeyOld); oVec.insert(vKeyNew, vValue);] Scala: ___ [can use: var vValue = oArray(vKeyOld); oArray = oArray.patch(vKeyOld, oArray.take(0), 1); oArray = oArray.patch(vKeyNew, Array(vValue), 0)] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: var vValue = oArray.remove(at:vKeyOld); oArray.insert(vValue, at:vKeyNew)] UFL: Array.Delete [delete a key, but maintain the positions of other keys][see also: VarDelete] AutoHotkey: oArray.Delete(vKey) C++: ___ C#: oArray[vKey] = null Crystal: oArray[vKey] = nil Excel: ___ Excel VBA: oArray(vKey) = Empty Go: ___ Java: oArray[vKey] = null JavaScript: delete oArray[vKey] [note: sets the key to empty (elided)] [also: oArray[vKey] = undefined] Kotlin: oArray[vKey] = null PHP: $oArray[$vKey] = null [also: unset($oArray[$vKey])] Python: oList[vKey] = None R: oArray[vKey] = NA [note: can't do: oArray[vKey] = NULL] Ruby: oArray[vKey] = nil Rust: oArray[vKey] = None [also: oVec[vKey] = None] [note: for arrays/vectors of options] Scala: oArray(vKey) = null [FIXME] SQL (MySQL): UPDATE MyTable SET v=NULL where k=MyValue [also (if not the last element, leaves a gap in the indexes): DELETE FROM MyTable WHERE k=MyValue] [FIXME] SQL (PostgreSQL): UPDATE MyTable SET v=NULL where k=MyValue [also (if not the last element, leaves a gap in the indexes): DELETE FROM MyTable WHERE k=MyValue] [also: (MyArray)[:MyKey-1] || ARRAY[NULL] || (MyArray)[MyKey+1:]] [note: 1-based] SQL (SQLite): UPDATE MyTable SET v=NULL where k==MyValue [also (if not the last element, leaves a gap in the indexes): DELETE FROM MyTable WHERE k==MyValue] Swift: oArray[vKey] = nil UFL: Array.Clear [or Array.DeleteAll/Array.Empty][remove all keys, e.g. set the array's length to 0, e.g. replace array with an empty array][see also: VarDelete/Array.OverwriteIntDemo] AutoHotkey: oArray.Length := 0 [also: oArray := []] [deprecated (AHK v1): oArray.Delete(oArray.MinIndex(), oArray.MaxIndex())] C++: ___ [can use (for array on the heap): oArray = new int[0]] [also: oVec.clear()] [also: oVec = {}] [WARNING: oVec.empty() returns whether the vector is empty or not] C#: Array.Resize(ref oArray, 0) Crystal: oArray.clear Excel: ___ Excel VBA: ReDim oArray(0) Go: oSlice = nil [also (with different side effects): oSlice = oSlice[:0]] [note: both return a slice with 0 elements] Java: oArray = new int[]{} JavaScript: oArray.length = 0 Kotlin: oArray.clear() PHP: $oArray = [] [also: array_splice($oArray, 0, count($oArray))] [note: appears to work even if the array has no '0' key] Python: oList.clear() R: oVec = head(oVec, 0) Ruby: oArray.clear Rust: oVec.clear() Scala: oArrayNew = oArray.take(0) SQL (MySQL): DELETE FROM MyTable SQL (PostgreSQL): DELETE FROM MyTable [also: (MyArray)[:0]] SQL (SQLite): DELETE FROM MyTable Swift: oArray.removeAll() UFL: Array.Clone [or Array.Copy][copy the entire array][see also: Array.SliceTo/Array.SliceUntil] AutoHotkey: oArrayNew := oArray.Clone() C++: std::copy(std::begin(oArray), std::end(oArray), std::begin(oArrayNew)) [also: std::copy(std::begin(oArray), std::end(oArray), oArrayNew)] [also: auto oVecNew = oVec] [also: std::vector<int> oVecNew(oVec)] [also: std::copy(oVec.begin(), oVec.end(), std::back_inserter(oVecNew))] [note: 'oArrayNew = oArray' causes an error] [requires (copy): #include <algorithm>] C#: oArrayNew = oArray.Clone() as string[] [also: oArrayNew = (string[])oArray.Clone()] [also: oArrayNew = oArray[..]] [also: oArrayNew = oArray.ToArray()] [note: replace 'string[]' with the appropriate type e.g. int[]/double[]] [WARNING (Clone): if omit the array type, can get 'Cannot apply indexing with [] to an expression of type 'object'' error] [requires (ToArray): using System.Linq] Crystal: oArrayNew = oArray.clone [also: oArrayNew = oArray.dup] Excel: ___ Excel VBA: oArrayNew = oArray [WARNING: this creates a copy, not a reference] [i.e. in many languages, this syntax would result in 2 variables pointing to the same object] Go: oArrayNew := oArray [MAJOR WARNING: 'oArrayNew := oArray' clones, 'oSliceNew := oSlice' creates a reference] [WARNING: copies (clones) the object, not a reference: oArrayNew := oArray] [also (clones the object): oSliceNew := slices.Clone(oSlice)] [also (creates a reference): oSliceNew := oSlice] Java: oArrayNew = oArray.clone() JavaScript: oArrayNew = oArray.slice() Kotlin: oArrayNew = oArray.copyOf() PHP: $oArrayNew = $oArray [WARNING: this creates a copy, not a reference] Python: oListNew = oList.copy() R: oVecNew = oVec [WARNING: this creates a copy, not a reference] Ruby: oArrayNew = oArray.clone [also: oArrayNew = oArray.dup] [also: initialize_clone, initialize_dup, initialize_copy] Rust: oArrayNew = oArray.clone() [note: also works with vectors] [WARNING: this creates a copy, not a reference: oArrayNew = oArray] [WARNING: Rust makes a distinction between clone and copy] Scala: oArrayNew = oArray.clone SQL (MySQL): CREATE TABLE MyTableNew AS SELECT * FROM MyTable SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT * FROM MyTable SQL (SQLite): CREATE TABLE MyTableNew AS SELECT * FROM MyTable Swift: oArrayNew = oArray [WARNING: this creates a copy, not a reference] [also: oArrayNew = oArray.map{$0}] UFL: Array.SliceTo [create a copy of keys a (inclusive) to b (inclusive)][inclusive end: less common, but more intuitive (than exclusive end)][WARNING: array 'slices' are often references to keys, rather than copies of keys (i.e. often modifying the slice, modifies the original)] AutoHotkey: ___ C++: auto oVecNew = std::vector<std::string>(oVec.begin()+vKey1, oVec.begin()+vKey2+1) C#: var oArrayNew = oArray[vKey1..(vKey2+1)] [also: var oArrayNew = oArray.ToList().Take(vKey1..(vKey2+1)).ToArray()] [WARNING: in C#, '..' is end exclusive] [requires (ToList): using System.Linq] [note (both): returns an array] Crystal: oArrayNew = oArray[vKey1..vKey2] [note: returns an array] Excel: ___ Excel VBA: ___ Go: oSliceNew := oArray[vKey1 : vKey2+1] [note: returns a slice] Java: var oArrayNew = Arrays.copyOfRange(oArray, vKey1, vKey2+1) [WARNING: appends default values if endpoint goes beyond array] [requires (Arrays): import java.util.*] [note: returns an array] JavaScript: oArrayNew = oArray.slice(vKey1, vKey2+1) [note: returns an array] Kotlin: oArrayNew = oArray.slice(vKey1..vKey2).toTypedArray() PHP: $oArrayNew = array_slice($oArray, $vKey1, $vKey2-$vKey1+1) [note: returns an array] Python: oListNew = oList[vKey1:vKey2+1] [note: returns a list] R: oVecNew = oVec[vKey1:vKey2] [note: returns a vector] Ruby: oArrayNew = oArray[vKey1..vKey2] [note: returns an array] Rust: oVecNew: Vec<_> = oArray[vKey1..=vKey2].iter().collect() [note: also works with vectors] Scala: oArrayNew = oArray.slice(vKey1, vKey2+1) [note: returns an array] [FIXME] SQL (MySQL): SELECT * FROM MyTable WHERE k BETWEEN MyKey1 AND MyKey2 [FIXME] SQL (PostgreSQL): SELECT * FROM MyTable WHERE k BETWEEN MyKey1 AND MyKey2 [also: (MyArray)[MyKey1:MyKey2]] SQL (SQLite): SELECT * FROM MyTable WHERE k BETWEEN MyKey1 AND MyKey2 Swift: oArrayNew = Array(oArray[vKey1...vKey2]) UFL: Array.SliceUntil [create a copy of keys a (inclusive) to b (exclusive)] AutoHotkey: ___ C++: auto oVecNew = std::vector<std::string>(oVec.begin()+vKey1, oVec.begin()+vKey2) C#: var oArrayNew = oArray[vKey1..vKey2] [also: var oArrayNew = oArray.ToList().Take(vKey1..vKey2).ToArray()] [WARNING: in C#, '..' is end exclusive] [requires (ToList): using System.Linq] [note (both): returns an array] Crystal: oArrayNew = oArray[vKey1...vKey2] [note: returns an array] Excel: ___ Excel VBA: ___ Go: oSliceNew := oArray[vKey1 : vKey2] [note: returns a slice] Java: var oArrayNew = Arrays.copyOfRange(oArray, vKey1, vKey2) [WARNING: appends default values if endpoint goes beyond array] [requires (Arrays): import java.util.*] [note: returns an array] JavaScript: oArrayNew = oArray.slice(vKey1, vKey2) [note: returns an array] Kotlin: oArrayNew = oArray.slice(vKey1..<vKey2).toTypedArray() PHP: $oArrayNew = array_slice($oArray, $vKey1, $vKey2-$vKey1) [note: returns an array] Python: oListNew = oList[vKey1:vKey2] [note: returns a list] R: oVecNew = oVec[vKey1:(vKey2-1)] [note: returns a vector] Ruby: oArrayNew = oArray[vKey1...vKey2] [note: returns an array] Rust: oVecNew: Vec<_> = oArray[vKey1..vKey2].iter().collect() [note: also works with vectors] [WARNING: in Rust, '..' is end exclusive] Scala: oArrayNew = oArray.slice(vKey1, vKey2) [note: returns an array] [FIXME] SQL (MySQL): SELECT * FROM MyTable WHERE k BETWEEN MyKey1 AND MyKey2-1 [FIXME] SQL (PostgreSQL): SELECT * FROM MyTable WHERE k BETWEEN MyKey1 AND MyKey2-1 [also: (MyArray)[MyKey1:MyKey2-1]] SQL (SQLite): SELECT * FROM MyTable WHERE k BETWEEN MyKey1 AND MyKey2-1 Swift: oArrayNew = Array(oArray[vKey1..<vKey2]) UFL: Array.SliceRest [create a copy of keys from key onwards][see also: Array.RemoveFirstMult/Array.RemoveAtRest] AutoHotkey: ___ [can use: oArrayNew := oArray.Clone(), oArrayNew.RemoveAt(1, vKey-1)] C++: auto oVecNew = std::vector<std::string>(oVec.begin()+vKey, oVec.end()) C#: var oArrayNew = oArray[vKey..] [also: var oArrayNew = oArray.ToList().Take(vKey..).ToArray()] [WARNING: in C#, '..' is end exclusive] [requires (ToList): using System.Linq] [note (both): returns an array] Crystal: oArrayNew = oArray[vKey..] [note: returns an array] Excel: ___ Excel VBA: ___ Go: oSliceNew := oArray[vKey:] [note: returns a slice] Java: var oArrayNew = Arrays.copyOfRange(oArray, vKey, oArray.length) [WARNING: appends default values if endpoint goes beyond array] [requires (Arrays): import java.util.*] [note: returns an array] JavaScript: oArrayNew = oArray.slice(vKey) [note: returns an array] Kotlin: oArrayNew = oArray.slice(vKey..<oArray.size).toTypedArray() [WARNING: can't do 'oArray.slice(vKey..)'] PHP: $oArrayNew = array_slice($oArray, $vKey) [note: returns an array] Python: oListNew = oList[vKey:] [note: returns a list] R: oVecNew = oVec[-(1:(vKey-1))] [note: returns a vector] Ruby: oArrayNew = oArray[vKey..] [note: returns an array] Rust: oVecNew: Vec<_> = oArray[vKey..].iter().collect() [note: also works with vectors] Scala: oArrayNew = oArray.slice(vKey, oArray.length) [note: returns an array] [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE k < MyKey; [also: SELECT * FROM MyTable WHERE k >= MyKey] [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE k < MyKey; [also: SELECT * FROM MyTable WHERE k >= MyKey] [also: (MyArray)[MyKey:]] SQL (SQLite): DELETE FROM MyTable WHERE k < MyKey; [also: SELECT * FROM MyTable WHERE k >= MyKey] Swift: oArrayNew = Array(oArray[vKey...]) UFL: (Array.SliceRestInfRangeDemo) [demonstrating syntax for ranges with an infinite upper bound] AutoHotkey: ___ C++: ___ C#: oArray[vKey..] Crystal: oArray[vKey..] Excel: ___ Excel VBA: ___ Go: oArray[vKey:] Java: ___ JavaScript: ___ Kotlin: ___ [WARNING: can't do 'oArray.slice(vKey..)'] PHP: ___ Python: oList[vKey:] R: ___ Ruby: oArray[vKey..] Rust: oArray[vKey..] Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): (MyArray)[MyKey:] SQL (SQLite): ___ Swift: oArray[vKey...] UFL: Array.SliceFirst [or Array.Left/Array.TakeAsArray/Array.TakeFirstAsArray/Array.TakeLeftAsArray/Array.FirstMult][create a copy of first n keys][see also: Array.First] AutoHotkey: ___ C++: auto oVecNew = std::vector<std::string>(oVec.begin(), oVec.begin()+vCount) C#: var oArrayNew = oArray[..vCount] [also: var oArrayNew = oArray.Take(vCount).ToArray()] [WARNING: in C#, '..' is end exclusive] [note (both): returns an array] Crystal: oArrayNew = oArray[...vCount] [note: returns an array] Excel: ___ Excel VBA: ___ Go: oSliceNew := oArray[:vCount] [note: returns a slice] Java: var oArrayNew = Arrays.copyOfRange(oArray, 0, Math.min(vCount, oArray.length)) [requires (Arrays): import java.util.*] [note: returns an array] JavaScript: oArrayNew = oArray.slice(0, vCount) [note: returns an array] Kotlin: oArrayNew = oArray.take(vCount).toTypedArray() [also: oArrayNew = oArray.slice(0..<vCount).toTypedArray()] PHP: $oArrayNew = array_slice($oArray, 0, $vCount) [note: returns an array] Python: oListNew = oList[:vCount] [note: returns a list] R: oVecNew = head(oVec, vCount) [note: returns a vector] Ruby: oArrayNew = oArray[...vCount] [note: returns an array] Rust: oVecNew: Vec<_> = oArray[0..vCount].iter().collect() [note: also works with vectors] [WARNING: in Rust, '..' is end exclusive] Scala: oArrayNew = oArray.take(vCount) [note: returns an array] [FIXME] SQL (MySQL): SELECT * FROM MyTable ORDER BY k LIMIT MyCount [FIXME] SQL (PostgreSQL): SELECT * FROM MyTable ORDER BY k LIMIT MyCount [also: (MyArray)[:MyKey]] SQL (SQLite): SELECT * FROM MyTable ORDER BY k LIMIT MyCount Swift: oArrayNew = Array(oArray.prefix(vCount)) UFL: Array.SliceLast [or Array.Right/Array.TakeLastAsArray/Array.TakeRightAsArray/Array.LastMult][create a copy of last n keys][see also: Array.Last] AutoHotkey: ___ C++: auto oVecNew = std::vector<std::string>(oVec.end()-vCount, oVec.end()) C#: var oArrayNew = oArray[Math.Max(oArray.Length-vCount, 0)..] [also: var oArrayNew = oArray.TakeLast(vCount).ToArray()] [also: var oArrayNew = oArray[^vCount..]] [WARNING: in C#, '..' is end exclusive] [note (all): returns an array] Crystal: oArrayNew = oArray[-vCount..] [note: returns an array] Excel: ___ Excel VBA: ___ Go: oSliceNew := oArray[len(oArray)-vCount:] [note: returns a slice] Java: var oArrayNew = Arrays.copyOfRange(oArray, Math.max(oArray.length-vCount, 0), oArray.length) [requires (Arrays): import java.util.*] [note: returns an array] JavaScript: oArrayNew = oArray.slice(-vCount) [note: returns an array] Kotlin: oArrayNew = oArray.takeLast(vCount).toTypedArray() PHP: $oArrayNew = array_slice($oArray, -$vCount) [note: returns an array] Python: oListNew = oList[-vCount:] [note: returns a list] R: oVecNew = tail(oVec, vCount) [note: returns a vector] Ruby: oArrayNew = oArray[-vCount..] [note: returns an array] Rust: oVecNew: Vec<_> = oArray[oArray.len()-vCount..].iter().collect() [note: also works with vectors] [WARNING: in Rust, '..' is end exclusive] Scala: oArrayNew = oArray.takeRight(vCount) [note: returns an array] [FIXME] SQL (MySQL): SELECT * FROM (SELECT * FROM MyTable ORDER BY k DESC LIMIT MyCount) ORDER BY k [also (in descending order): SELECT * FROM MyTable ORDER BY k DESC LIMIT MyCount] [FIXME] SQL (PostgreSQL): SELECT * FROM (SELECT * FROM MyTable ORDER BY k DESC LIMIT MyCount) ORDER BY k [also (in descending order): SELECT * FROM MyTable ORDER BY k DESC LIMIT MyCount] [also: (MyArray)[cardinality(MyArray)-MyCount+1:]] SQL (SQLite): SELECT * FROM (SELECT * FROM MyTable ORDER BY k DESC LIMIT MyCount) ORDER BY k [also (in descending order): SELECT * FROM MyTable ORDER BY k DESC LIMIT MyCount] Swift: oArrayNew = Array(oArray.suffix(vCount)) UFL: Array.First [get the value of the first key][see also: Array.SliceFirst] AutoHotkey: vValue := oArray[1] [note: 1-based] C++: vValue = oArray[0] [also: vValue = oVec[0]] C#: vValue = oArray[0] [also: vValue = oArray.First()] [requires (First): using System.Linq] Crystal: vValue = oArray[0] [also: vValue = oArray.first] [also: vValue = oArray.first?] Excel: ___ Excel VBA: vValue = oArray(0) Go: vValue := oArray[0] Java: vValue = oArray[0] [also: vValue = oList.get(0)] JavaScript: vValue = oArray[0] [also (iterator): vValue = oMap.keys().next().value] Kotlin: vValue = oArray[0] [also: vValue = oArray.first()] PHP: $vValue = $oArray[0] [note: get value of first key added to array/map: $vValue = array_first($oArray)] [note: get name of first key added to array/map: $vKey = array_key_first($oArray)] Python: vValue = oList[0] R: vValue = oVec[1] [also: vValue = head(oVec, 1)] [note: 1-based] Ruby: vValue = oArray[0] [also: vValue = oArray.first] Rust: vValue = oArray[0] [also: vValue = oArray.first().unwrap()] [note (both): also works with vectors] Scala: vValue = oArray.head [note: oArray.tail returns everything except the first element as an array] SQL (MySQL): SELECT v FROM MyTable WHERE k=1 [also: SELECT v FROM MyTable ORDER BY k LIMIT 1] SQL (PostgreSQL): SELECT v FROM MyTable WHERE k=1 [also: SELECT v FROM MyTable ORDER BY k LIMIT 1] [also: (MyArray)[1]] SQL (SQLite): SELECT v FROM MyTable WHERE k==1 [also: SELECT v FROM MyTable ORDER BY k LIMIT 1] Swift: vValue = oArray[0] [also: vValue = oArray.first!] UFL: Array.Last [get the value of the last key][see also: Array.Length/Array.Pop/Array.SliceLast] AutoHotkey: vValue := oArray[-1] [also: vValue := oArray[oArray.Length]] [deprecated (AHK v1): vValue := oArray[oArray.Length()]] [note: 1-based] C++: vValue = oArray[sizeof(oArray)/sizeof(oArray[0])-1] [also: vValue = oVec.back()] C#: vValue = oArray[oArray.Length-1] [also: vValue = oArray.Last()] [also: vValue = oArray.TakeLast(1).Last()] [also: vValue = oArray.TakeLast(1).ToArray()[0]] [also: vValue = oArray[^1]] [note: oArray[^1] returns the last element, oArray[^vNum] returns the nth-to-last element, ^vNum creates an Index instance] [requires (Last): using System.Linq] Crystal: vValue = oArray[-1] [also: vValue = oArray[oArray.size-1]] [also: vValue = oArray.last] [also: vValue = oArray.last?] Excel: ___ Excel VBA: vValue = oArray(UBound(oArray)) Go: vValue := oArray[len(oArray)-1] Java: vValue = oArray[oArray.length-1] [also: vValue = oList.get(oList.size()-1)] JavaScript: vValue = oArray.at(-1) [also: vValue = oArray[oArray.length-1]] [also: vValue = oArray.slice(-1)[0]] Kotlin: vValue = oArray.last() [also: vValue = oArray[oArray.size-1]] [also: vValue = oArray.takeLast(1)[0]] PHP: $vValue = $oArray[count($oArray)-1] [also: $vValue = array_slice($oArray, -1)[0]] [note: get value of last key added to array/map: $vValue = array_last($oArray) ] [note: get name of last key added to array/map: $vKey = array_key_last($oArray)] Python: vValue = oList[-1] [also: vValue = oList[len(oList)-1]] R: vValue = tail(oVec, 1) [also: vValue = oVec[length(oVec)]] [note: 1-based] Ruby: vValue = oArray[-1] [also: vValue = oArray[oArray.length-1]] [also: vValue = oArray.last] Rust: vValue = oArray[oArray.len()-1] [also: vValue = oArray.last().unwrap()] [note: also works with vectors] Scala: vValue = oArray.last [note: oArray.tail returns everything except the first element as an array] SQL (MySQL): SELECT v FROM MyTable ORDER BY k DESC LIMIT 1 [also: SELECT v FROM MyTable WHERE k=(SELECT max(k) FROM MyTable)] SQL (PostgreSQL): SELECT v FROM MyTable ORDER BY k DESC LIMIT 1 [also: SELECT v FROM MyTable WHERE k=(SELECT max(k) FROM MyTable)] [also: (MyArray)[array_upper(MyArray, 1)]] SQL (SQLite): SELECT v FROM MyTable ORDER BY k DESC LIMIT 1 [also: SELECT v FROM MyTable WHERE k==(SELECT max(k) FROM MyTable)] [also: SELECT v FROM (SELECT max(k),v FROM MyTable)] Swift: vValue = oArray.last! [also: vValue = oArray[oArray.count-1]] UFL: Array.ToString [or: Array.ToStr][array to string][see also: Array.Join/String/Array.Print/JsonFromObj/ObjToString] AutoHotkey: ___ C++: ___ C#: ___ [can use: vText = String.Join(vSep, oArray)] Crystal: vText = oArray.to_s Excel: ___ [can use: TEXTJOIN()] Excel VBA: ___ [can use: vText = Join(oArray, vSep)] Go: vText := fmt.Sprintf("%v", oArray) Java: vText = java.util.Arrays.toString(oArray) [also (for string arrays): vText = String.join(vSep, oArray)] [WARNING (only prints a type name): oArray.toString()] JavaScript: vText = String(oArray) [also: vText = oArray.toString()] [also: vText = JSON.stringify(oArray)] Kotlin: vText = oArray.contentToString() [also: vText = oArray.toList().toString()] [also (uses comma-space separator): vText = oArray.joinToString()] [WARNING (only prints a type name): oArray.toString()] PHP: ___ [can use: $vText = implode($vSep, $oArray)] [alias (implode): join] [also: $vText = var_export($oArray, true)] [also: $vText = print_r($oArray, true)] Python: vText = str(oList) R: vText = toString(oVec) [also: vText = capture.output(print(oVec))] Ruby: vText = oArray.to_s Rust: vText = format!("{:?}", oArray) [can use: vText = oArray.join(vSep)] [also: vText = format!("{:#?}", oArray)] [note: also works with vectors] Scala: ___ [can use: vText = oArray.mkString(vSep)] [also: vText = String.join(vSep, oArray)] [also: vText = oArray.toList.toString] [WARNING (only prints a type name): oArray.toString] SQL (MySQL): ___ [can use: SELECT group_concat(v ORDER BY k SEPARATOR MySep) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): ___ [can use: SELECT string_agg(v, MySep ORDER BY k) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] [also: MyArray::text] SQL (SQLite): ___ [can use: SELECT group_concat(v, MySep ORDER BY k) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] [also: string_agg()] Swift: vText = String(describing:oArray) [also: vText = oArray.description] [also: vText = String(reflecting:oArray)] [also (for string arrays): vText = oArray.joined(separator:vSep)] UFL: Array.Concat [join array items into one string, with no separator strings between items] AutoHotkey: ___ C++: ___ [can use (string array): std::string vText = std::accumulate(std::begin(oArray), std::end(oArray), std::string(""))] [also (string vector): std::string vText = std::accumulate(oVec.begin(), oVec.end(), std::string(""))] [requires (accumulate): #include <numeric>] C#: vText = String.Concat(oArray) Crystal: vText = oArray.join Excel: ___ [can use: =TEXTJOIN("",, MyText1, MyText2, MyText3)] [version: Excel 2016: TEXTJOIN()] Excel VBA: vText = Join(oArray, "") Go: vText := strings.Join(oArray, "") [note: for string arrays only] Java: vText = String.join("", oArray) [note: for string arrays only] [also (String[]): vText = Arrays.stream(oArray).map(Object::toString).collect(Collectors.joining())] [also (int[]): vText = Arrays.stream(oArray).boxed().map(Object::toString).collect(Collectors.joining())] [requires (Collectors): import java.util.stream.*] JavaScript: vText = oArray.join("") Kotlin: vText = oArray.joinToString("") PHP: $vText = implode("", $oArray) [alias (implode): join] [also: $vText = implode($oArray)] Python: vText = "".join(oList) [WARNING: can't do: oList.join("")] [note: for string lists only] [also (any list): vText = "".join(map(str, oList))] R: vText = paste(oVec, collapse="") Ruby: vText = oArray.join Rust: vText = oArray.concat() [also: vText = oVec.concat()] [note (both): for string arrays only] [also (any array): vText = oArray.map(|v| format!("{}", v)).concat()] [also (any vector): vText = oVec.iter().map(|v| format!("{}", v)).collect::<Vec<_>>().concat()] Scala: vText = oArray.mkString("") [also: vText = String.join("", oArray)] SQL (MySQL): SELECT group_concat(v ORDER BY k SEPARATOR '') FROM MyTable [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): SELECT string_agg(v, '' ORDER BY k) FROM MyTable [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] [also: array_to_string(MyArray, '')] [also: array_to_string(MyArray, '', MyNullStr)] SQL (SQLite): SELECT group_concat(v, '' ORDER BY k) FROM MyTable [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] [also: string_agg()] Swift: vText = oArray.joined() [note: for string arrays only] [also (any array): vText = oArray.map{String($0)}.joined()] UFL: Array.Join [join array items into one string, with a separator string between each item][see also: Array.ToString] AutoHotkey: ___ C++: ___ [can use (string array): std::string vText = std::accumulate(std::begin(oArray), std::end(oArray), std::string(""), [&vSep](std::string a,std::string v){return a+v+vSep;})] [also (string vector): std::string vText = std::accumulate(oVec.begin(), oVec.end(), std::string(""), [&vSep](std::string a,std::string v){return a+v+vSep;})] [WARNING (both): adds a trailing separator] [requires (accumulate): #include <numeric>] [note: can replace '[&vSep]' with '[vSep]'] C#: vText = String.Join(vSep, oArray) Crystal: vText = oArray.join(vSep) [note: no separator if omitted] Excel: ___ [can use: =TEXTJOIN(MySep,, MyText1, MyText2, MyText3)] [version: Excel 2016: TEXTJOIN()] Excel VBA: vText = Join(oArray, vSep) [note: separator is space if omitted] Go: vText := strings.Join(oArray, vSep) [note: for string arrays only] [can use (any array, space-separated): vText := fmt.Sprintf("%v", oArray); vText = string([]rune(vText)[1 : len([]rune(vText))-1])] [note (Join): can't omit separator] Java: vText = String.join(vSep, oArray) [note: for string arrays only] [can use (any array, comma-space-separated): vText = java.util.Arrays.toString(oArray); vText = vText.substring(1, vText.length()-1)] [also (String[]): vText = Arrays.stream(oArray).map(Object::toString).collect(Collectors.joining(vSep))] [also (int[]): vText = Arrays.stream(oArray).boxed().map(Object::toString).collect(Collectors.joining(vSep))] [requires (Collectors): import java.util.stream.*] JavaScript: vText = oArray.join(vSep) [note: separator is comma if omitted] Kotlin: vText = oArray.joinToString(vSep) [note: separator is comma-space if omitted] PHP: $vText = implode($vSep, $oArray) [alias (implode): join] [also (no separator): $vText = implode($oArray)] [deprecated: implode($oArray, $vSep)] Python: vText = vSep.join(oList) [WARNING: can't do: oList.join(vSep)] [note: for string lists only] [also (any list): vText = vSep.join(map(str, oList))] R: vText = paste(oVec, collapse=vSep) [note: if 'collapse' omitted, double-space separated, and quotes used if strings] [also: vText = paste(oVec1, oVec2, sep=vSepCol, collapse=vSepRow)] [e.g. paste(c("A","B","C"), c("a","b","c"), sep=":", collapse=",") returns 'A:a,B:b,C:c'] Ruby: vText = oArray.join(vSep) [note: no separator if omitted] Rust: vText = oArray.join(vSep) [also: vText = oVec.join(vSep)] [note (both): for string arrays only] [also (any array): vText = oArray.map(|v| format!("{}", v)).join(vSep)] [also (any vector): vText = oVec.iter().map(|v| format!("{}", v)).collect::<Vec<_>>().join(vSep)] [note: can't omit separator] Scala: vText = oArray.mkString(vSep) SQL (MySQL): SELECT group_concat(v ORDER BY k SEPARATOR MySep) FROM MyTable [note: separator is comma if omitted] [MAJOR WARNING: does not sort: SELECT group_concat(v SEPARATOR '|') FROM MyTable ORDER BY k] [MAJOR WARNING: does not sort: SELECT group_concat(v SEPARATOR '|') FROM (SELECT v FROM MyTable ORDER BY k) oTemp] SQL (PostgreSQL): SELECT string_agg(v, MySep ORDER BY k) FROM MyTable [note: can't omit separator] [also: SELECT string_agg(v, MySep) FROM (SELECT v FROM MyTable ORDER BY k) oTemp] [also: array_to_string(MyArray, MySep)] [also: array_to_string(MyArray, MySep, MyNullStr)] SQL (SQLite): SELECT group_concat(v, MySep ORDER BY k) FROM MyTable [note: separator is comma if omitted] [also: SELECT group_concat(v, MySep) FROM (SELECT v FROM MyTable ORDER BY k)] [MAJOR WARNING: does not sort: SELECT group_concat(v, MySep) FROM MyTable ORDER BY k] [version: SQLite 3.44: group_concat(v, MySep ORDER BY k)] [also: string_agg()] Swift: vText = oArray.joined(separator:vSep) [note: for string arrays only] [also (any array): vText = oArray.map{String($0)}.joined(separator:vSep)] [note (joined): no separator if omitted] UFL: Array.JoinMult [join array items into one string, specify an array of pad strings][note: alternating pad strings(/join strings/separator strings)][e.g. ["a","b","c","d","e","f"].Join([":",":",","]) = "a:b:c,d:e:f"][see 'Array.JoinChunk' for similar more limited functionality][see also: StrSplitMult/Array.JoinChunk] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.JoinChunk) [or Array.JoinInOut/Array.JoinTwoLevel][join array items into one string: split array into chunks, join items within chunks with inner separator, join chunks with outer separator][e.g. ["a","b","c","d","e","f"].JoinChunk(3, ":", ",") = "a:b:c,d:e:f"][note: this is a workaround for a common use case of Array.JoinMult, which many languages lack][algorithm: array chunk, array map using array join, array join (array -> 2D array -> string array -> string)] AutoHotkey: ___ C++: ___ C#: vText = String.Join(vSepOut, oArray.Chunk(vCount).Select(v=>String.Join(vSepIn, v))) [requires (Select): using System.Linq] Crystal: vText = oArray.each_slice(vCount).map{|v| v.join(vSepIn)}.join(vSepOut) Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: oChunks = Array(Math.ceil(oArray.length/vCount)).fill().map((v,k)=>oArray.slice(k*vCount, k*vCount+vCount)); vText = oChunks.map(v=>v.join(vSepIn)).join(vSepOut);] Kotlin: vText = oArray.toList().chunked(vCount).map{it.joinToString(vSepIn)}.joinToString(vSepOut) PHP: $vText = implode($vSepOut, array_map(fn($v)=>implode($vSepIn, $v), array_chunk($oArray, $vCount))) Python: vText = vSepOut.join(map(lambda v:vSepIn.join(v), itertools.batched(oList, vCount))) [requires: import itertools] [also: vText = vSepOut.join([vSepIn.join(v) for v in itertools.batched(oList, vCount)])] R: vText = paste(mapply(\(v) paste(v, collapse=vSepIn), split(oVec, ceiling(seq_along(oVec)/vCount))), collapse=vSepOut) Ruby: vText = oArray.each_slice(vCount).map{|v| v.join(vSepIn)}.join(vSepOut) Rust: vText = oVec.chunks(vCount).map(|v| v.to_vec().join(vSepIn)).collect::<Vec<_>>().join(vSepOut) Scala: vText = oArray.grouped(vCount).map{_.mkString(vSepIn)}.mkString(vSepOut) SQL (MySQL): ___ [can use: SELECT group_concat(v SEPARATOR MySepOut) FROM (SELECT group_concat(v ORDER BY k SEPARATOR MySepIn) AS v FROM MyTable GROUP BY (k-1) DIV MyCount+1) oTemp] SQL (PostgreSQL): ___ [can use: SELECT string_agg(v, MySepOut) FROM (SELECT string_agg(v, MySepIn ORDER BY k) AS v FROM MyTable GROUP BY (k-1)/MyCount+1) oTemp] SQL (SQLite): ___ [can use: SELECT group_concat(v, MySepOut) FROM (SELECT group_concat(v, MySepIn ORDER BY k) AS v FROM MyTable GROUP BY (k-1)/MyCount+1)] Swift: ___ [can use: var oChunks = stride(from:0, to:oArray.count, by:vCount).map{Array(oArray[$0..<min($0+vCount, oArray.count)])}; var vText = oChunks.map{$0.joined(separator:vSepIn)}.joined(separator:vSepOut)]] UFL: Array.Sort [or Array.SortDefault][sort array items, use default comparison (default sort order)][note: modifies the array][see also: Array.Sorted] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [WARNING: Sort() is case-insensitive by default (to sort case-sensitively: use mode 'C')] [note: to sort numerically: use mode 'N' e.g. vText := Sort(vText, "D" vSep " N")] [also: maps use alphabetical order for strings, and numerical order for ints, i.e. add items to a map, then do a for loop on the map to retrieve the items in order] C++: std::sort(std::begin(oArray), std::end(oArray)) [also: std::sort(oVec.begin(), oVec.end())] [also: std::stable_sort] [WARNING: sort() is an unstable sort, however, this doesn't matter for integer or case-sensitive sorting] [requires (sort/stable_sort): #include <algorithm>] C#: Array.Sort(oArray) [also: Array.Sort(oArray, StringComparer.Ordinal)] [also: oArray = oArray.OrderBy(v=>v, StringComparer.Ordinal).ToArray()] [requires (OrderBy): using System.Linq] [WARNING: Array.Sort(oArray) uses the default comparer for strings, which may give undesirable results, e.g. case-insensitive with lower-case first, e.g. 'E,Q,W,e,q,w' to 'e,E,q,Q,w,W'] Crystal: oArray.sort! Excel: ___ Excel VBA: ___ Go: slices.Sort(oSlice) [also: slices.SortFunc/slices.SortStableFunc] [also: slices.IsSorted] Java: Arrays.sort(oArray) [note: e.g. works on int[] and String[]] [also: Collections.sort(oList)] [requires (Arrays): import java.util.*] [note: separates positive/negative zero] JavaScript: oArray.sort() [WARNING: default sort is alphabetical, to sort numerically: e.g. oArray.sort((v1,v2)=>v1-v2)] Kotlin: oArray.sort() [also: oArray.sortWith(oFunc)] [note: separates positive/negative zero] PHP: sort($oArray) [also: usort($oArray, $oFunc)] [WARNING: default sort (SORT_REGULAR): sorts strings alphabetically (compares 2 strings numerically if at least 1 is numeric-looking, a 'numeric string'), sorts ints numerically] [note: to sort alphabetically: e.g. sort($oArray, SORT_STRING)] [note: to sort numerically: e.g. sort($oArray, SORT_NUMERIC)] Python: oList.sort() [WARNING: default sort: sorts strings alphabetically, sorts ints numerically (no special handling for numeric-looking strings), throws if try to compare int with str] [note: to sort strings numerically: e.g. oList.sort(key=int)] R: ___ [can use: oVec = sort(oVec)] [also: oList = oList[order(sapply(oList, `[[`, i=1))]] [also: oVec = sort(oVec, method="radix")] [see also: Array.SortCasSen for info about locales] Ruby: oArray.sort! Rust: oArray.sort() [also: oVec.sort()] [WARNING: sort() fails on floats] [can use (floats, throws on NaNs): oArray.sort_by(|v1,v2| v1.partial_cmp(v2).unwrap())] Scala: ___ [can use: oArray = oArray.sorted] [note: separates positive/negative zero] SQL (MySQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] [also: array_sort(MyArray)] [also: array_sort(MyArray, MyIsDesc, MyIsNullsFirst)] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] Swift: oArray.sort() UFL: Array.SortNum [sort array items, numeric comparison][note: modifies the array][note: some sort functions use the word 'order'][note: state if sort separates positive/negative zero][see also: Array.SortStrAsInt/Array.SortStrAsFloat/Array.SortStrAsNum] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [WARNING (Sort): default sort is alphabetical (case insensitive), to sort numerically: use mode 'N' e.g. vText := Sort(vText, "D" vSep " N")] C++: std::sort(std::begin(oArray), std::end(oArray)) [also: std::sort(oVec.begin(), oVec.end())] [also: std::stable_sort] [WARNING: sort() is an unstable sort, however, this doesn't matter for integer or case-sensitive sorting] [requires (sort/stable_sort): #include <algorithm>] C#: Array.Sort(oArray) Crystal: oArray.sort! Excel: ___ Excel VBA: ___ Go: slices.Sort(oSlice) [also: slices.SortFunc/slices.SortStableFunc] [also: slices.IsSorted] Java: Arrays.sort(oArray) [note: e.g. works on int[] and String[]] [also: Collections.sort(oList)] [requires (Arrays): import java.util.*] [note: separates positive/negative zero] JavaScript: ___ [can use: oArray.sort((v1,v2)=>v1-v2)] [WARNING: default sort is alphabetical] Kotlin: oArray.sort() [also: oArray.sortWith(oFunc)] [note: separates positive/negative zero] PHP: sort($oArray) [also: usort($oArray, $oFunc)] Python: oList.sort() R: ___ [can use: oVec = sort(oVec)] [also: oList = oList[order(sapply(oList, `[[`, i=1))]] Ruby: oArray.sort! Rust: oArray.sort() [also: oVec.sort()] [WARNING: sort() fails on floats] [can use (floats, throws on NaNs): oArray.sort_by(|v1,v2| v1.partial_cmp(v2).unwrap())] Scala: ___ [can use: oArray = oArray.sorted] [note: separates positive/negative zero] SQL (MySQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] Swift: oArray.sort() UFL: Array.SortCasSen [sort array items, case-sensitive comparison][note: modifies the array][sorts case-sensitive, according to Unicode codepoints, e.g. 'Q,q,w,W,E,e,r,R' to 'E,Q,R,W,e,q,r,w'][note: some sort functions use the word 'order'][see also: StrAlphabetize/Array.SortNumAsStr] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [WARNING: Sort() is case-insensitive by default (to sort case-sensitively: use mode 'C')] [note: Sort(): default sort is alphabetical, to sort numerically: use mode 'N' e.g. vText := Sort(vText, "D" vSep " N")] C++: std::sort(std::begin(oArray), std::end(oArray)) [also: std::sort(oVec.begin(), oVec.end())] [also: std::stable_sort] [WARNING: sort() is an unstable sort, however, this doesn't matter for integer or case-sensitive sorting] [requires (sort/stable_sort): #include <algorithm>] C#: Array.Sort(oArray, StringComparer.Ordinal) [also: oArray = oArray.OrderBy(v=>v, StringComparer.Ordinal).ToArray()] [requires (OrderBy): using System.Linq] [WARNING: Array.Sort(oArray) uses the default comparer for strings, which may give undesirable results, e.g. case-insensitive with lower-case first, e.g. 'E,Q,W,e,q,w' to 'e,E,q,Q,w,W'] Crystal: oArray.sort! Excel: ___ Excel VBA: ___ Go: slices.Sort(oSlice) [also: slices.SortFunc/slices.SortStableFunc] [also: slices.IsSorted] Java: Arrays.sort(oArray) [note: e.g. works on int[] and String[]] [also: Collections.sort(oList)] [requires (Arrays): import java.util.*] JavaScript: oArray.sort() [WARNING: default sort is alphabetical, to sort numerically: e.g. oArray.sort((v1,v2)=>v1-v2)] Kotlin: oArray.sort() [also: oArray.sortWith(oFunc)] PHP: sort($oArray) [also: usort($oArray, $oFunc)] [WARNING: default sort (SORT_REGULAR): sorts strings alphabetically (compares 2 strings numerically if at least 1 is numeric-looking, a 'numeric string'), sorts ints numerically] [note: to sort alphabetically: e.g. sort($oArray, SORT_STRING)] [note: to sort numerically: e.g. sort($oArray, SORT_NUMERIC)] Python: oList.sort() [WARNING: default sort: sorts strings alphabetically, sorts ints numerically (no special handling for numeric-looking strings), throws if try to compare int with str] [note: to sort strings numerically: e.g. oList.sort(key=int)] R: ___ [can use: oVec = sort(oVec, method="radix")] [note: 'radix' sorts by Unicode codepoints] [note (sort by locale, which may or may not be case-sensitive): oVec = sort(oVec)] [note: get locale (e.g. 'en_US.UTF-8'): Sys.getlocale("LC_COLLATE")] [note: set locale to case-sensitive: e.g. Sys.setlocale("LC_COLLATE", "C")] [also: oList = oList[order(sapply(oList, `[[`, i=1))]] Ruby: oArray.sort! Rust: oArray.sort() [also: oVec.sort()] Scala: ___ [can use: oArray = oArray.sorted] SQL (MySQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable ORDER BY v] [note (descending order): append ' DESC'] Swift: oArray.sort() UFL: Array.SortCasIns [sort array items, case-insensitive comparison][note: modifies the array][typically compares strings as if both were lower case (or both upper case), e.g. 'Q,q,w,W,E,e,r,R' to 'E,e,Q,q,r,R,w,W'][see also: StrAlphabetizeCasIns/Array.SortLocale/Array.SortNumAsStr] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [WARNING (Sort): default sort is alphabetical, to sort numerically: use 'N' mode e.g. vText := Sort(vText, "D" vSep " N")] [WARNING: Sort() is case-insensitive by default] C++: ___ C#: Array.Sort(oArray, StringComparer.OrdinalIgnoreCase) [also: oArray = oArray.OrderBy(v=>v, StringComparer.OrdinalIgnoreCase).ToArray()] [requires (OrderBy): using System.Linq] Crystal: ___ [can use: oArray.sort!{|v1,v2| v1.downcase <=> v2.downcase}] [also (true indicates case-insensitive): oArray.sort!{|v1,v2| v1.to_s.compare(v2.to_s, true)}] Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.sort(oArray, String::compareToIgnoreCase) [also: Collections.sort(oList, String.CASE_INSENSITIVE_ORDER)] [requires (Arrays): import java.util.*] JavaScript: ___ [can use: oArray.sort((v1,v2) => v1.localeCompare(v2, undefined, {sensitivity: "accent"}))] [note (sensitivity/strength): 'accent' considers 'E'/'e' identical, 'case' considers 'e'/'é' identical, 'base' considers all 3 identical, 'variant' considers none identical] Kotlin: oArray.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER, {it})) [also: oArray.sortBy{it.lowercase()}] PHP: usort($oArray, "strcasecmp") [also: sort($oArray, SORT_FLAG_CASE | SORT_STRING)] Python: ___ [can use: oList.sort(key=str.casefold)] [also: oList.sort(key=str.lower)] R: ___ [can use: oVec = oVec[order(tolower(oVec))]] Ruby: oArray.sort!(&:casecmp) Rust: ___ Scala: ___ [can use: oArrayNew = oArray.sortWith(_.toLowerCase < _.toLowerCase)] [note: also works with lists] [FIXME] SQL (MySQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v COLLATE NOCASE] [note (descending order): append ' DESC'] [also: SELECT * FROM MyTable ORDER BY lower(v)] [note: can use upper() instead of lower()] [FIXME] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable ORDER BY v COLLATE NOCASE] [note (descending order): append ' DESC'] [also: SELECT * FROM MyTable ORDER BY lower(v)] [note: can use upper() instead of lower()] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable ORDER BY v COLLATE NOCASE] [note (descending order): append ' DESC'] [also: SELECT * FROM MyTable ORDER BY lower(v)] [note: can use upper() instead of lower()] Swift: oArray.sort{$0.caseInsensitiveCompare($1) == .orderedAscending} [requires: import Foundation] UFL: (Array.SortCasInsThenSen) [sort array items, case-insensitive comparison, tiebreaker: case-sensitive comparison, e.g. 'Q,q,w,W,E,e,r,R' to 'E,e,Q,q,R,r,W,w'][note: modifies the array][note: where stable sort exists (preserves the order of items considered equal), you can sort sensitive, then insensitive][WARNING: note the different order (insensitive/sensitive): approach 1: case-insensitive sort with case-sensitive tiebreaking, approach 2: case-sensitive sort then case-insensitive sort][a multi-stage sort] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [e.g. vText := Sort(Sort(vText, "D" vSep " C"), "D" vSep)] [WARNING: Sort() is case-insensitive by default] C++: ___ C#: oArrayNew = oArray.OrderBy(v=>v, StringComparer.OrdinalIgnoreCase).ThenBy(v=>v, StringComparer.Ordinal).ToArray() [requires (OrderBy): using System.Linq] [WARNING: Array.Sort() appears to use stable sort within one sort, but not between multiple sorts] Crystal: ___ [can use: oArray.sort!; oArray.sort!{|v1,v2| v1.downcase <=> v2.downcase}] [also (true indicates case-insensitive): oArray.sort!; oArray.sort!{|v1,v2| v1.to_s.compare(v2.to_s, true)}] Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.sort(oArray); Arrays.sort(oArray, String::compareToIgnoreCase); [also: Collections.sort(oList); Collections.sort(oList, String.CASE_INSENSITIVE_ORDER);] [requires (Arrays): import java.util.*] JavaScript: ___ [can use: oArray.sort((v1,v2) => v1.localeCompare(v2, undefined, {sensitivity: "accent"}) || (+(v1>v2)||-(v1<v2)));] Kotlin: oArray.sort(); oArray.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER, {it})) [also: oArray.sort(); oArray.sortBy{it.lowercase()}] PHP: sort($oArray); usort($oArray, "strcasecmp"); [also: sort($oArray); sort($oArray, SORT_FLAG_CASE | SORT_STRING);] Python: ___ [can use: oList.sort(); oList.sort(key=str.casefold)] [also: oList.sort(); oList.sort(key=str.lower)] R: ___ [can use: oVec = sort(oVec, method="radix"); oVec = oVec[order(tolower(oVec))]] Ruby: oArray.sort!; oArray.sort!(&:casecmp) Rust: ___ Scala: ___ [can use: oArrayNew = oArray.sorted.sortWith(_.toLowerCase < _.toLowerCase)] [note: also works with lists] [FIXME] SQL (MySQL): ___ [e.g. SELECT * FROM MyTable ORDER BY lower(v), v] [FIXME] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable ORDER BY lower(v), v] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable ORDER BY lower(v), v] Swift: oArray.sort(); oArray.sort{$0.caseInsensitiveCompare($1) == .orderedAscending} [requires: import Foundation] UFL: Array.SortLocale [note: for code examples not specifying a locale, results depend on the current locale e.g. 'C', 'en_US.UTF-8', 'en_US', 'en'][WARNING: 'en_US.UTF-8' sorts case-insensitive, with a tiebreaker that (unusually) puts lower case then upper case, e.g. 'Q,q,w,W,E,e,r,R' to 'e,E,q,Q,r,R,w,W'] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [note: can use (CL for locale, but differs from LC_COLLATE): Sort(vText, "D" vSep " CL")] [note: can use DllCall with msvcrt\_wsetlocale (or msvcrt\setlocale) to get/set the locale, but this doesn't affect Sort()] C++: ___ C#: Array.Sort(oArray) [also: Array.Sort(oArray, Comparer.DefaultInvariant)] [requires (Comparer): using System.Collections] [e.g. set locale: System.Globalization.CultureInfo.CurrentCulture = new CultureInfo(vLocale, false)] [e.g. get locale, can use (also: .Name): vName = System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: Collections.sort(oList, oColl) [beforehand: e.g. oColl = Collator.getInstance(new Locale("en", "US"))] [beforehand: e.g. oColl = Collator.getInstance()] [requires (Collator): import java.text.*] JavaScript: oArray.sort(new Intl.Collator(vLocale).compare) Kotlin: oArray.sortWith(compareBy(oColl){it}) [beforehand: e.g. oColl = java.text.Collator.getInstance(java.util.Locale("en", "US"))] [beforehand: e.g. oColl = java.text.Collator.getInstance()] PHP: sort($oArray, SORT_LOCALE_STRING) [e.g. set locale: setlocale(LC_COLLATE, $vLocale)] [e.g. get locale: $vLocale = setlocale(LC_COLLATE, 0)] Python: oList.sort(key=locale.strxfrm) [requires: import locale] [e.g. set locale: locale.setlocale(locale.LC_COLLATE, vLocale)] [e.g. get locale: vLocale = locale.getlocale(locale.LC_COLLATE)] R: ___ [can use: oVec = sort(oVec)] [e.g. set locale: Sys.setlocale("LC_COLLATE", vLocale)] [e.g. get locale: vLocale = Sys.getlocale("LC_COLLATE")] Ruby: ___ Rust: ___ Scala: ___ [can use: var oList = java.util.Arrays.stream(oArray).collect(java.util.stream.Collectors.toList()); java.util.Collections.sort(oList, oColl); oArray = oList.toArray().map(v=>v.toString);] [beforehand: e.g. oColl = java.text.Collator.getInstance(java.util.Locale("en", "US"))] [beforehand: e.g. oColl = java.text.Collator.getInstance()] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray.sort{$0.localizedCompare($1) == .orderedAscending} [requires: import Foundation] [e.g. get locale: Locale.current.languageCode] UFL: Array.SortNatural [or Array.SortLogical][natural sort order][e.g. ["a1","a11","A2","a22"] to ["a1","A2","a11","a22"]] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [note: to sort logically: use mode 'CLogical' e.g. vText := Sort(vText, "D" vSep " CLogical")] [note: uses the Winapi's StrCmpLogicalW internally] [note: case-insensitive] C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oArray.sort(new Intl.Collator(undefined, {numeric:true, sensitivity:"base"}).compare) [note: case-insensitive] Kotlin: ___ PHP: natcasesort($oArray) [also (case-sensitive): natsort($oArray)] [note (both): sort in-place] Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray.sort{$0.localizedStandardCompare($1) == .orderedAscending} [requires: import Foundation] [note: case-insensitive] UFL: Array.SortCustom [sort array by a custom sort comparator function, that typically takes 2 values and returns 1/0/-1][note: for the examples below, state below if comparator function doesn't return 1/0/-1] AutoHotkey: ___ [can use (sort string by delimiter): Sort(vText, "D" vSep, oFunc)] C++: std::stable_sort(std::begin(oArray), std::end(oArray), oFunc) [also: std::stable_sort(oVec.begin(), oVec.end(), oFunc)] [WARNING: a comparator function should return a bool: 'comparison function object ... which returns true if the first argument is less than ... the second'] [also (for a comparator function that returns 1/0/-1): std::stable_sort(std::begin(oArray), std::end(oArray), [&oFunc](std::string v1, std::string v2) {return oFunc(v1, v2) < 0;})] C#: Array.Sort(oArray, oFunc) Crystal: oArray.sort!(&oFunc) Excel: ___ Excel VBA: ___ Go: slices.SortStableFunc(oSlice, oFunc) [note: SortFunc/SortStableFunc/SortedFunc/SortedStableFunc] Java: ___ [can use (string array): Arrays.sort(oArray, oCmp)] [can use (int array): oArrayNew = Arrays.stream(oArray).boxed().sorted(oCmp).mapToInt(v->v).toArray()] [e.g. string comparator: Comparator<String> oCmp = (String v1, String v2) -> v1.compareTo(v2)] [e.g. int comparator (for Integer type): Comparator<Integer> oCmp = (Integer v1, Integer v2) -> v1.compareTo(v2)] JavaScript: oArray.sort(oFunc) Kotlin: oArray.sortWith(oFunc) PHP: usort($oArray, $oFunc) Python: oList.sort(key=cmp_to_key(oFunc)) [requires: from functools import cmp_to_key] R: ___ [note: can use custom classes to achieve custom sorts, e.g. to sort vectors/lists] Ruby: oArray.sort!(&oFunc) Rust: oArray.sort_by(|v1,v2| oFunc(v1,v2).cmp(&0)) [e.g. string array: oArray.sort_by(|v1,v2| oFunc(v1.to_string(),v2.to_string()).cmp(&0))] [e.g. int array: oArray.sort_by(|v1,v2| oFunc(*v1,*v2).cmp(&0))] [note: 1/0/-1 to Ordering: vCmp.cmp(&0)] [note: Ordering to 1/0/-1: oOrder as i32] [note: also works with vectors] Scala: oArrayNew = oArray.sortWith(oFunc) [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray.sort{oFunc($0,$1) < 0} [WARNING: comparator function should return a bool: 'A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false'] UFL: Array.SortCustomDemo [or Array.SortCustomTemplate][sort array by a custom sort comparator function that works as similarly to the default as possible (as a template for a custom function)][WARNING: when comparing numbers, use a 'compare' function if possible, rather than a-b, to avoid overflow, which can give the wrong result] AutoHotkey: ___ [can use (sort string by delimiter, string values): Sort(vText, "D" vSep, (v1,v2,vOffset) => StrCompare(v1, v2) || -vOffset)] [can use (sort string by delimiter, numeric values): Sort(vText, "D" vSep, (v1,v2,vOffset) => (v1-v2) || -vOffset)] [WARNING: AHK v1: || returns 1 or 0 (AHK v2: || returns a value)] C++: ___ [e.g. string array: std::stable_sort(std::begin(oArray), std::end(oArray), [](std::string v1, std::string v2) {return v1.compare(v2) < 0;})] [e.g. int array: std::stable_sort(std::begin(oArray), std::end(oArray), [](int v1, int v2) {return v1-v2 < 0;});] [WARNING: a comparator function should return a bool] C#: Array.Sort(oArray, (v1,v2)=>v1.CompareTo(v2)) Crystal: oArray.sort!{|v1,v2| v1 <=> v2} Excel: ___ Excel VBA: ___ Go: ___ [e.g. string slice: slices.SortStableFunc(oSlice, func(v1, v2 string) int { return strings.Compare(v1, v2) })] [e.g. int slice: slices.SortStableFunc(oSlice, func(v1, v2 int) int { return cmp.Compare(v1, v2) })] Java: ___ [can use (string array): Arrays.sort(oArray, (v1,v2) -> v1.compareTo(v2))] [can use (int array): oArrayNew = Arrays.stream(oArray).boxed().sorted((v1,v2) -> v1.compareTo(v2)).mapToInt(v->v).toArray()] JavaScript: ___ [can use: oArray.sort((v1,v2)=>+(v1>v2)||-(v1<v2))] [also (ints): oArray.sort((v1,v2)=>v1-v2)] Kotlin: oArray.sortWith{v1,v2->compareValues(v1,v2)} PHP: ___ [can use (string array): usort($oArray, fn($v1,$v2)=>substr_compare($v1, $v2, 0))] [can use (int array): usort($oArray, fn($v1,$v2)=>$v1<=>$v2)] Python: oList.sort(key=cmp_to_key(lambda v1,v2 : +(v1>v2) or -(v1<v2))) [requires: from functools import cmp_to_key] R: ___ Ruby: oArray.sort!{|v1,v2| v1 <=> v2} Rust: oArray.sort_by(|v1,v2| v1.cmp(v2)) [note: also works with vectors] Scala: ___ [can use: oArrayNew = oArray.sortWith(_ < _)] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: oArray.sort{$0 < $1}] [can use (string array): oArray.sort{$0.compare($1).rawValue < 0}] [can use (int array): oArray.sort{$0-$1 < 0}] [requires (compare): import Foundation] UFL: Array.SortByCustom [or Array.SortByKeyCustom/Array.SortByTransformFuncCustom][sort an array, but don't compare the values directly, compare transformed versions of the values][sort array by a custom key function, that takes 1 value and returns an intermediate form (the intermediate forms are compared using the default comparator for the type)][related terms: decorate-sort-undecorate, strxfrm ('string transform'), Schwartzian transform] AutoHotkey: ___ [can use (sort string by delimiter, string values): Sort(vText, "D" vSep, (v1,v2,vOffset) => StrCompare(oFunc(v1), oFunc(v2)) || -vOffset)] [can use (sort string by delimiter, numeric values): Sort(vText, "D" vSep, (v1,v2,vOffset) => (oFunc(v1)-oFunc(v2)) || -vOffset)] [WARNING: AHK v1: || returns 1 or 0 (AHK v2: || returns a value)] C++: ___ [can use (string array): std::stable_sort(std::begin(oArray), std::end(oArray), [&oFunc](std::string v1, std::string v2) {return oFunc(v1).compare(oFunc(v2)) < 0;})] [can use (int array): std::stable_sort(std::begin(oArray), std::end(oArray), [&oFunc](int v1, int v2) {return oFunc(v1)-oFunc(v2) < 0;});] C#: oArrayNew = oArray.OrderBy(v=>oFunc(v)).ToArray() [requires (OrderBy): using System.Linq] [also: Array.Sort(oArray, (v1,v2)=>oFunc(v1).CompareTo(oFunc(v2)))] Crystal: oArray.sort_by!(&oFunc) Excel: ___ Excel VBA: ___ Go: ___ [can use (string slice): slices.SortStableFunc(oSlice, func(v1, v2 string) int { return strings.Compare(oFunc(v1), oFunc(v2)) })] [can use (int slice): slices.SortStableFunc(oSlice, func(v1, v2 int) int { return cmp.Compare(oFunc(v1), oFunc(v2)) })] Java: ___ [can use (string array): Arrays.sort(oArray, (v1,v2) -> oFunc.apply(v1).compareTo(oFunc.apply(v2)))] [can use (int array): oArrayNew = Arrays.stream(oArray).boxed().sorted((v1,v2) -> oFunc.apply(v1).compareTo(oFunc.apply(v2))).mapToInt(v->v).toArray()] JavaScript: ___ [can use: oArray.sort((v1,v2)=>+(oFunc(v1)>oFunc(v2))||-(oFunc(v1)<oFunc(v2)))] Kotlin: oArray.sortBy(oFunc) PHP: ___ [can use (string array): usort($oArray, fn($v1,$v2)=>substr_compare($oFunc($v1), $oFunc($v2), 0))] [can use (int array): usort($oArray, fn($v1,$v2)=>$oFunc($v1)<=>$oFunc($v2))] Python: oList.sort(key=oFunc) R: ___ [can use: oVecNew = oVec[order(mapply(oFunc, oVec))]] [also: oVecNew = oVec[order(oFunc(oVec))]] Ruby: oArray.sort_by!(&oFunc) Rust: oArray.sort_by_key(|v| oFunc(v)) [e.g. string array: oArray.sort_by_key(|v| oFunc(v.to_string()))] [e.g. int array: oArray.sort_by_key(|v| oFunc(*v))] [also: sort_by_cached_key] [WARNING: sort_by takes a 2-param comparator function, not a 1-param transform function] [note: also works with vectors] Scala: oArrayNew = oArray.sortBy(oFunc) SQL (MySQL): ___ [e.g. SELECT * FROM MyTable ORDER BY char_length(v)] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable ORDER BY length(v)] [WARNING 'ORDER BY length(v)' puts nulls at the end, unlike in MySQL/SQLite, workaround: length(coalesce(v, ''))] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable ORDER BY length(v)] Swift: ___ [can use: oArray.sort{oFunc($0) < oFunc($1)}] [can use (string array): oArray.sort{oFunc($0).compare(oFunc($1)).rawValue < 0}] [can use (int array): oArray.sort{oFunc($0)-oFunc($1) < 0}] [requires (compare): import Foundation] UFL: Array.SortStrAsInt [e.g. ["1","11","111","2","22","222"] to ["1","2","11","22","111","222"]] [e.g. treat non-numbers as 0] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [note: to sort numerically: use mode 'N' e.g. vText := Sort(vText, "D" vSep " N")] C++: ___ C#: Array.Sort(oArray, (v1,v2)=>Int32.Parse(v1).CompareTo(Int32.Parse(v2))) Crystal: oArray.sort!{|v1,v2| v1.to_i <=> v2.to_i} Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.sort(oArray, (v1,v2)->Integer.compare(Integer.parseInt(v1),Integer.parseInt(v2))) [requires (Arrays): import java.util.*] JavaScript: oArray.sort((v1,v2)=>parseInt(v1)-parseInt(v2)) [also: oArray.sort((v1,v2)=>v1-v2)] Kotlin: oArray.sortWith{v1,v2->compareValues(v1.toInt(),v2.toInt())} PHP: usort($oArray, fn($v1,$v2)=>intval($v1)<=>intval($v2)) [also: sort($oArray, SORT_NUMERIC)] Python: oList.sort(key=int) R: ___ [can use: oVec = oVec[order(as.integer(oVec))]] Ruby: oArray.sort!{|v1,v2| v1.to_i <=> v2.to_i} Rust: oArray.sort_by(|v1,v2| v1.parse::<i32>().unwrap().cmp(&v2.parse::<i32>().unwrap())) [note: also works with vectors] Scala: ___ [can use: oArrayNew = oArray.sortWith(_.toInt < _.toInt)] [FIXME] SQL (MySQL): ___ [can use: SELECT * FROM MyTable ORDER BY CAST(v AS INTEGER)] [FIXME] SQL (PostgreSQL): ___ [can use: SELECT * FROM MyTable ORDER BY CAST(v AS INTEGER)] SQL (SQLite): ___ [can use: SELECT * FROM MyTable ORDER BY CAST(v AS INTEGER)] Swift: oArray.sort{Int($0)! <= Int($1)!} UFL: Array.SortStrAsFloat [or Array.SortStrAsNum] [e.g. ["1","11","111","2","22","222"] to ["1","2","11","22","111","222"]] [e.g. treat non-numbers as 0] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [note: to sort numerically: use mode 'N' e.g. vText := Sort(vText, "D" vSep " N")] C++: ___ C#: Array.Sort(oArray, (v1,v2)=>Double.Parse(v1).CompareTo(Double.Parse(v2))) Crystal: oArray.sort!{|v1,v2| v1.to_f <=> v2.to_f} Excel: ___ Excel VBA: ___ Go: ___ Java: Arrays.sort(oArray, (v1,v2)->Double.compare(Double.parseDouble(v1),Double.parseDouble(v2))) [requires (Arrays): import java.util.*] JavaScript: oArray.sort((v1,v2)=>v1-v2) [also: oArray.sort((v1,v2)=>parseFloat(v1)-parseFloat(v2))] Kotlin: oArray.sortWith{v1,v2->compareValues(v1.toDouble(),v2.toDouble())} PHP: sort($oArray, SORT_NUMERIC) [also: usort($oArray, fn($v1,$v2)=>floatval($v1)<=>floatval($v2))] Python: oList.sort(key=float) R: ___ [can use: oVec = oVec[order(as.numeric(oVec))]] Ruby: oArray.sort!{|v1,v2| v1.to_f <=> v2.to_f} Rust: oArray.sort_by(|v1,v2| v1.parse::<f64>().unwrap().partial_cmp(&v2.parse::<f64>().unwrap()).unwrap()) [note: also works with vectors] Scala: ___ [can use: oArrayNew = oArray.sortWith(_.toDouble < _.toDouble)] [FIXME] SQL (MySQL): ___ [can use: SELECT * FROM MyTable ORDER BY CAST(v AS DOUBLE)] [FIXME] SQL (PostgreSQL): ___ [can use: SELECT * FROM MyTable ORDER BY CAST(v AS FLOAT)] SQL (SQLite): ___ [can use: SELECT * FROM MyTable ORDER BY CAST(v AS REAL)] Swift: oArray.sort{Double($0)! <= Double($1)!} UFL: Array.SortNumAsStr [e.g. [1,2,11,22,111,222] to [1,11,111,2,22,222]] AutoHotkey: ___ [note: Sort() can sort a string by a delimiter char] [note: to sort numerically: use mode 'N' e.g. vText := Sort(vText, "D" vSep " N")] C++: ___ C#: Array.Sort(oArray, (v1,v2)=>v1.ToString().CompareTo(v2.ToString())) Crystal: oArray.sort!{|v1,v2| v1.to_s <=> v2.to_s} Excel: ___ Excel VBA: ___ Go: slices.SortFunc(oSlice, func(v1, v2 int) int { return cmp.Compare(fmt.Sprintf("%v", v1), fmt.Sprintf("%v", v2)) }) [also: slices.SortStableFunc()] Java: oArray = Arrays.stream(oArray).boxed().sorted((v1,v2)->String.valueOf(v1).compareTo(String.valueOf(v2))).mapToInt(v->v).toArray() [requires (Arrays): import java.util.*] JavaScript: oArray.sort() [WARNING: default sort is alphabetical] Kotlin: oArray.sortWith{v1,v2->compareValues(v1.toString(),v2.toString())} PHP: sort($oArray, SORT_STRING) [also: usort($oArray, fn($v1,$v2)=>substr_compare($v1, $v2, 0, null, true))] Python: oList.sort(key=str) R: ___ [can use: oVec = oVec[order(as.character(oVec))]] Ruby: oArray.sort!{|v1,v2| v1.to_s <=> v2.to_s} Rust: oArray.sort_by(|v1,v2| v1.to_string().cmp(&v2.to_string())) [note: also works with vectors] Scala: ___ [can use: oArrayNew = oArray.sortWith(_.toString < _.toString)] SQL (MySQL): ___ [can use: SELECT * FROM MyTable ORDER BY '' || v] [requires (||): set sql_mode=PIPES_AS_CONCAT] [also: SELECT * FROM MyTable ORDER BY concat(v)] SQL (PostgreSQL): ___ [can use: SELECT * FROM MyTable ORDER BY '' || v] SQL (SQLite): ___ [can use: SELECT * FROM MyTable ORDER BY '' || v] Swift: oArray.sort{String($0) <= String($1)} UFL: Array.Sorted [or Array.SortedDefault][sort array items, use default comparison (default sort order)][note: doesn't modify the array (creates a new array)][note: methods ending 'ed' often return a new array, whereas other methods often modify an array][see also: Array.Sort/Array.Clone] AutoHotkey: ___ C++: ___ C#: ___ [can use: var oArrayNew = oArray[..]; Array.Sort(oArrayNew);] Crystal: oArrayNew = oArray.sort Excel: ___ Excel VBA: ___ Go: ___ [can use: oSliceNew := slices.Clone(oSlice); slices.Sort(oSliceNew)] [MAJOR WARNING: for arrays: 'a2 := a' clones, for slices: 's2 := s' creates a reference] Java: ___ [e.g. String[] oArrayNew = Arrays.stream(oArray).sorted().toArray(String[]::new)] [e.g. int[] oArrayNew = Arrays.stream(oArray).sorted().toArray()] [requires (Arrays): import java.util.*] JavaScript: oArrayNew = oArray.toSorted() Kotlin: oArrayNew = oArray.sorted() [also: oArray.sortedWith(oFunc)] PHP: ___ [can use: $oArrayNew = $oArray; sort($oArrayNew);] [WARNING: '$oArrayNew = $oArray' creates a copy, not a reference] Python: oListNew = sorted(oList) R: oVecNew = sort(oVec) [also: oListNew = oList[order(sapply(oList, `[[`, i=1))]] Ruby: oArrayNew = oArray.sort Rust: ___ [can use: let mut oArrayNew = oArray.clone(); oArrayNew.sort();] [note: also works with vectors] Scala: oArrayNew = oArray.sorted [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArrayNew = oArray.sorted() UFL: Array.SortByArray [or Array.SortByTransformArray/Array.SortByArrayRank][sort array A by array B, e.g. ["a","b","c","d","e"] by [5,3,4,1,2] gives ["d","e","b","c","a"], e.g. 1 is the 4th element, so the new 1st element is the old 4th element][i.e. 2 arrays of equal size, you copy array B and apply a default sort, the same moves are applied to array A, you discard the copy of array B][i.e. similar to sorting column B, and modifying column A to keep it in sync (keep rows intact), then returning column B to its original order][algorithm: e.g. zip (combine 2 arrays as array of pairs), sort (by 2nd item in pair), map (to get 1st items from pairs, discard 2nd items)][see also: Array.Zip/Array.SortByCustom] AutoHotkey: ___ C++: ___ [can use: std::vector<std::pair<std::string,int>> oVecTemp; std::transform(std::begin(oArray), std::end(oArray), std::begin(oArrayRank), std::back_inserter(oVecTemp), [](const auto&v1, const auto&v2) {return std::make_pair(v1, v2);}); std::stable_sort(std::begin(oVecTemp), std::end(oVecTemp), [](auto p1, auto p2) {return p1.second < p2.second;}); std::vector<std::string> oVecNew; std::transform(std::begin(oVecTemp), std::end(oVecTemp), std::back_inserter(oVecNew), [](const auto&p) {return p.first;});] [requires (transform): #include <algorithm>] [requires (pair): #include <utility>] C#: oArrayNew = oArray.Zip(oArrayRank, (v1,v2)=>(v1,v2)).OrderBy(e=>e.v2).Select(e=>e.v1).ToArray() [requires (OrderBy/Select): using System.Linq] Crystal: oArrayNew = oArray.zip(oArrayRank).sort_by!{|v|v[1]}.map{|v|v[0]} Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: oListNew = IntStream.range(0, oArray.length).mapToObj(i->Map.entry(oArray[i],oArrayRank[i])).sorted((e1,e2)->e1.getValue().compareTo(e2.getValue())).map(e->e.getKey()).collect(Collectors.toList())] [requires (IntStream/Collectors): import java.util.stream.*] [requires (Map): import java.util.*] JavaScript: oArrayNew = oArray.map((v,k)=>[v,oArrayRank[k]]).sort((v1,v2)=>+(v1[1]>v2[1])||-(v1[1]<v2[1])).map(v=>v[0]) Kotlin: oArrayNew = oArray.zip(oArrayRank).sortedBy{p->p.second}.map{p->p.first}.toTypedArray() PHP: $oArrayNew = $oArray; array_multisort(array_values($oArrayPos), $oArrayNew); [also: $oArrayNew = array_map(null, $oArray, $oArrayRank); usort($oArrayNew, fn($e1,$e2)=>gettype($e1[1]) == "string" ? substr_compare($e1[1],$e2[1],0) : $e1[1]<=>$e2[1]); $oArrayNew = array_map(fn($e)=>$e[0], $oArrayNew);] [WARNING: array_multisort() would sort the rank array, avoid this by using array_values() to pass a clone] [WARNING: '$oArrayNew = $oArray' creates a copy, not a reference] [version: PHP 8.0: array_multisort() uses stable sort] Python: oListNew = list(map(lambda e:e[0], sorted(zip(oList, oListRank), key=lambda e:e[1]))) R: oVecNew = oVec[order(oVecRank)] Ruby: oArrayNew = oArray.zip(oArrayRank).sort_by!{|v|v[1]}.map{|v|v[0]} Rust: ___ [can use: let mut oVecTemp = oArray.into_iter().zip(oArrayRank.into_iter()).collect::<Vec<_>>(); oVecTemp.sort_by_key(|v| v.1); let mut oVecNew = oVecTemp.iter().map(|e| e.0).collect::<Vec<_>>();] Scala: oArrayNew = oArray.zip(oArrayRank).sortBy(_(1)).map(_(0)) SQL (MySQL): SELECT * FROM MyTable ORDER BY (SELECT v+0 FROM MyTableRank WHERE MyTable.k=MyTableRank.k) SQL (PostgreSQL): SELECT * FROM MyTable ORDER BY (SELECT v::int FROM MyTableRank WHERE MyTable.k=MyTableRank.k) [also: can change WHERE clause: WHERE MyTable.ctid=MyTableRank.ctid] SQL (SQLite): SELECT * FROM MyTable ORDER BY (SELECT v+0 FROM MyTableRank WHERE MyTable.k=MyTableRank.k) [also: can change WHERE clause: WHERE MyTable.rowid==MyTableRank.rowid] Swift: oArrayNew = zip(oArray, oArrayRank).sorted{$0.1<$1.1}.map{$0.0} UFL: Array.Reverse [reverse order of array items][note: modifies the array][see also: Array.Sort] AutoHotkey: ___ [can use (sort string by a delimiter char): vText := Sort(vText, "D" vSep, (v1,v2,vOffset)=>vOffset)] C++: std::reverse(std::begin(oArray), std::end(oArray)) [also: std::reverse(oVec.begin(), oVec.end())] [requires (reverse): #include <algorithm>] C#: Array.Reverse(oArray) Crystal: oArray.reverse! Excel: ___ Excel VBA: ___ Go: slices.Reverse(oSlice) Java: Collections.reverse(oList) [requires (Collections): import java.util.*] [also (reverse int[]): oArrayNew = IntStream.range(0, oArray.length).map(i->oArray[oArray.length-1-i]).toArray()] [also (reverse double[]): oArrayNew = IntStream.range(0, oArray.length).mapToDouble(i->oArray[oArray.length-1-i]).toArray()] [also (reverse String[]/Integer[]): creates a temporary list, and reverses the array: Collections.reverse(Arrays.asList(oArray))] [requires (IntStream): import java.util.stream.*] JavaScript: oArray.reverse() Kotlin: oArray.reverse() PHP: ___ [can use: $oArray = array_reverse($oArray)] [WARNING: array_reverse() creates a new array, it doesn't modify the existing array] Python: oList.reverse() [also: oList = oList[::-1]] R: ___ [can use: oVec = rev(oVec)] [WARNING: rev() creates a new vector, it doesn't modify the existing vector] Ruby: oArray.reverse! Rust: oArray.reverse() [also: oVec.reverse()] Scala: ___ [can use: oArray = oArray.reverse] [note: also works with lists] [FIXME] SQL (MySQL): UPDATE MyTable SET k=(SELECT COUNT(*) FROM MyTable)+1-k [FIXME] SQL (PostgreSQL): UPDATE MyTable SET k=(SELECT COUNT(*) FROM MyTable)+1-k [also: array_reverse(MyArray)] SQL (SQLite): UPDATE MyTable SET k=(SELECT COUNT(*) FROM MyTable)+1-k Swift: oArray.reverse() UFL: Array.Reversed [reverse order of array items][note: doesn't modify the array (creates a new array)] AutoHotkey: ___ C++: ___ C#: ___ [can use: oArrayNew = Enumerable.Range(1, oArray.Length).Select(i=>oArray[oArray.Length-i]).ToArray()] [also: oArrayNew = oArray.Select((v,k)=>new{k,v}).OrderByDescending(e=>e.k).Select(e=>e.v).ToArray()] [requires (Enumerable): using System.Linq] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: oArrayNew = oArray.reverse Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oArrayNew = oArray.toReversed() [also: oArrayNew = oArray.slice().reverse()] Kotlin: oArrayNew = oArray.reversed() PHP: $oArrayNew = array_reverse($oArray) [WARNING: array_reverse() creates a new array, it doesn't modify the existing array] Python: oListNew = list(reversed(oList)) [also: oListNew = oList[::-1]] R: oVecNew = rev(oVec) [WARNING: rev() creates a new vector, it doesn't modify the existing vector] Ruby: oArrayNew = oArray.reverse Rust: oVecNew = oArray.clone().into_iter().rev().collect::<Vec<_>>() [note: also works with vectors] Scala: oArrayNew = oArray.reverse [note: also works with lists] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ [also: array_reverse(MyArray)] SQL (SQLite): ___ Swift: oArrayNew = Array(oArray.reversed()) UFL: Array.Shuffle [or Array.SortRandom][sort array items, random order][note: modifies the array][see also: Array.Sort] AutoHotkey: ___ [can use (sort string by a delimiter char): vText := Sort(vText, "D" vSep " Random")] C++: std::shuffle(std::begin(oArray), std::end(oArray), oGen) [also: std::shuffle(oVec.begin(), oVec.end(), oGen)] [beforehand: std::random_device oRD; std::mt19937 oGen(oRD())] [deprecated: std::random_shuffle] [requires (shuffle): #include <algorithm>] C#: ___ [can use: var oArrayNew = oArray.OrderBy(v=>oRand.Next()).ToArray()] [beforehand: var oRand = new Random()] Crystal: oArray.shuffle! Excel: ___ Excel VBA: ___ Go: rand.Shuffle(len(oArray), func(v1, v2 int) { oArray[v1], oArray[v2] = oArray[v2], oArray[v1] }) [beforehand: rand.Seed(time.Now().UnixNano())] Java: Collections.shuffle(oList) [requires (Collections): import java.util.*] [WARNING: e.g. for String[]/Integer[] (but not int[]), 'Collections.shuffle(Arrays.asList(oArray))' creates a temporary list, and shuffles the array] JavaScript: ___ [can use: oArray.sort((v1,v2)=>(Math.random() < 0.5) ? -1 : 1)] Kotlin: oArray.shuffle() PHP: shuffle($oArray) Python: random.shuffle(oList) [requires: import random] R: ___ [can use: oVecNew = sample(oVec)] [also: set.seed()] Ruby: oArray.shuffle! Rust: oArray.shuffle(&mut thread_rng()) [requires: use rand::thread_rng] [requires: use rand::seq::SliceRandom] [note: also works with vectors] Scala: ___ [can use: oArrayNew = scala.util.Random.shuffle(oArray).toArray] [note: also works with lists] SQL (MySQL): ___ [can use: UPDATE MyTable JOIN (SELECT row_number() OVER (ORDER BY rand()) AS rn,k,v FROM MyTable) oTemp ON MyTable.k = oTemp.rn SET MyTable.v = oTemp.v] [also: SET @rn = 0; UPDATE MyTable t1 INNER JOIN (SELECT (@rn := @rn + 1) AS rn,k,v FROM (SELECT * FROM MyTable ORDER BY rand()) t3) t2 ON t1.k = t2.rn SET t1.v = t2.v;] [also (shuffles rows): SELECT * FROM MyTable ORDER BY rand()] [note (JOIN): puts 2 columns side-by-side] SQL (PostgreSQL): ___ [can use: WITH oTemp AS (SELECT row_number() OVER oWin AS rn,k,v FROM MyTable WINDOW oWin AS (ORDER BY random())) UPDATE MyTable SET v=oTemp.v FROM oTemp WHERE MyTable.k=oTemp.rn] [also (shuffles rows): SELECT * FROM MyTable ORDER BY random()] [also: array_shuffle(MyArray)] SQL (SQLite): ___ [can use: WITH oTemp AS (SELECT row_number() OVER oWin AS rn,k,v FROM MyTable WINDOW oWin AS (ORDER BY random())) UPDATE MyTable SET v=oTemp.v FROM oTemp WHERE MyTable.k==oTemp.rn] [also (shuffles rows): SELECT * FROM MyTable ORDER BY random()] [version: SQLite 3.33: UPDATE FROM support] Swift: oArray.shuffle() UFL: Array.Shuffled [sort array items, random order][note: doesn't modify the array (creates a new array)] AutoHotkey: ___ C++: ___ C#: var oArrayNew = oArray.OrderBy(v=>oRand.Next()).ToArray() [beforehand: var oRand = new Random()] Crystal: oArrayNew = oArray.shuffle Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: oListNew = random.sample(oList, len(oList)) [requires: import random] R: oVecNew = sample(oVec) [also: set.seed()] Ruby: oArrayNew = oArray.shuffle Rust: ___ Scala: oArrayNew = scala.util.Random.shuffle(oArray).toArray [note: also works with lists] SQL (MySQL): ___ [can use: CREATE TABLE MyTableNew (k INTEGER PRIMARY KEY AUTO_INCREMENT, v TEXT); INSERT INTO MyTableNew SELECT NULL,v FROM MyTable ORDER BY rand();] SQL (PostgreSQL): ___ [can use: CREATE TABLE MyTableNew (k SERIAL PRIMARY KEY, v TEXT); INSERT INTO MyTableNew (v) SELECT v FROM MyTable ORDER BY random();] [also: array_shuffle(MyArray)] SQL (SQLite): ___ [can use: CREATE TABLE MyTableNew (k INTEGER PRIMARY KEY, v TEXT) STRICT; INSERT INTO MyTableNew SELECT NULL,v FROM MyTable ORDER BY random();] Swift: oArrayNew = oArray.shuffled() UFL: Array.Distinct [or Array.Unique/Array.Dedup/Array.RemoveDups/Array.RemoveDuplicates][remove duplicates, preserve order][see also: Array.ToSet] AutoHotkey: ___ C++: ___ [can use: for (const auto& vValue : oArray) if (!oMap.count(vValue)) oMap[vValue] = 1, oVecNew.push_back(vValue)] [beforehand (map): std::map<std::string,int> oMap] [beforehand (map/set): std::vector<std::string> oVecNew] [WARNING: std::unique only removes adjacent duplicates] [also (using set): for (const auto& vValue : oArray) if (!oSet.count(vValue)) oSet.insert(vValue), oVecNew.push_back(vValue)] [beforehand (set): std::unordered_set<std::string> oSet] [requires (set): #include <unordered_set>] C#: var oArrayNew = oArray.Distinct().ToArray() Crystal: oArrayNew = oArray.uniq [also (modifies array): oArray.uniq!] Excel: ___ Excel VBA: ___ Go: ___ [can use (doesn't preserve order): oSliceNew := slices.Clone(oSlice); slices.Sort(oSliceNew); oSliceNew = slices.Compact(oSliceNew)] [note: slices.Compact removes consecutive duplicates] Java: ___ [e.g. String[] oArrayNew = Arrays.stream(oArray).distinct().toArray(String[]::new)] [e.g. int[] oArrayNew = Arrays.stream(oArray).distinct().toArray()] [e.g. List<Integer>/List<String>: var oListNew = oList.stream().distinct().collect(Collectors.toList())] [note (all): preserves order] [requires (Collectors): import java.util.stream.*] JavaScript: oArrayNew = [...new Set(oArray)] [note: preserves order] Kotlin: oArrayNew = oArray.distinct() [also: oArray.distinctBy()] [note: preserves order] PHP: $oArrayNew = array_values(array_unique($oArray)) [WARNING: array_unique() creates a new array, it doesn't modify the existing array] [WARNING: array_unique() maintains indexes, use array_values() to reindex an array] [note: preserves order] Python: oListNew = list(dict.fromkeys(oList)) [note: preserves order] R: oVecNew = unique(oVec) [note: preserves order] Ruby: oArrayNew = oArray.uniq [also (modifies array): oArray.uniq!] Rust: oVecNew: Vec<_> = oVec.into_iter().unique().collect() [requires (unique): use itertools::Itertools] [WARNING: dedup() only removes adjacent duplicates] Scala: oArrayNew = oArray.distinct [note: preserves order] [note: also works with lists] SQL (MySQL): ___ [can use: CREATE TABLE MyTableNew (k INTEGER PRIMARY KEY AUTO_INCREMENT, v TEXT); INSERT INTO MyTableNew SELECT DISTINCT NULL,v FROM MyTable;] [also: SELECT min(k),v FROM MyTable GROUP BY v ORDER BY min(k)] [WARNING: 'GROUP BY' returns 1 row per group] SQL (PostgreSQL): ___ [can use: CREATE TABLE MyTableNew (k SERIAL PRIMARY KEY, v TEXT); INSERT INTO MyTableNew (v) SELECT DISTINCT v FROM MyTable;] [also: SELECT min(k),v FROM MyTable GROUP BY v ORDER BY min(k)] [WARNING: 'GROUP BY' returns 1 row per group] [also: array_agg(DISTINCT v) FROM unnest(MyArray) v] [also (doesn't preserve order): ARRAY(SELECT DISTINCT v FROM unnest(MyArray) v)] SQL (SQLite): ___ [can use: CREATE TABLE MyTableNew (k INTEGER PRIMARY KEY, v TEXT); INSERT INTO MyTableNew SELECT DISTINCT NULL,v FROM MyTable;] [also: SELECT min(k),v FROM MyTable GROUP BY v ORDER BY min(k)] [WARNING: 'GROUP BY' returns 1 row per group] Swift: ___ [can use: oArrayNew = oArray.reduce(into:[]){$0.contains($1) ?():$0.append($1)}] [note: preserves order] [also (doesn't preserve order): oArrayNew = Array(Set(oArray))] UFL: Array.FreqCount [or Array.FrequencyCount][return a map/dictionary][frequency table, preserve order] AutoHotkey: ___ C++: ___ [can use: for (const auto& vValue : oArray) oMap[vValue]++] [also: for (const auto& vValue : oArray) oMap[vValue] = oMap.count(vValue) ? oMap[vValue]+1 : 1] [beforehand: std::map<std::string,int> oMap] [WARNING: if vKey doesn't exist, 'oMap[vKey]++' creates a key with the default value, e.g. 0, then increments it] C#: ___ [e.g. int array: var oDict = oArray.GroupBy(v=>v).Select(g=>new[]{g.Key,g.Count()}).ToDictionary(e=>e[0], e=>e[1])] [e.g. string array: var oDict = oArray.GroupBy(v=>v).Select(g=>new KeyValuePair<string,int>(g.Key,g.Count())).ToDictionary(e=>e.Key, e=>e.Value)] [requires (KeyValuePair): using System.Collections.Generic] [requires (GroupBy/Select/ToDictionary): using System.Linq] Crystal: ___ [can use: oMap = oArray.each_with_object(Hash(String,Int32).new(0)){|v,o| o[v]+=1}] [note: Hash(String,Int32).new(0) creates a map with default value 0] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [e.g. Map<String,Long> oMap = Arrays.stream(oArray).collect(Collectors.groupingBy(e->e, LinkedHashMap::new, Collectors.counting()))] [e.g. Map<Integer,Long> oMap = Arrays.stream(oArray).boxed().collect(Collectors.groupingBy(e->e, LinkedHashMap::new, Collectors.counting()))] [e.g. List<Integer>/List<String>: var oMap = oList.stream().collect(Collectors.groupingBy(e->e, LinkedHashMap::new, Collectors.counting()))] [note (all): preserves order] [requires (Collectors): import java.util.stream.*] JavaScript: ___ [can use: for (const vValue of oArray) oMap.set(vValue, (oMap.get(vValue)||0) + 1)] [beforehand: oMap = new Map()] [note: preserves order] Kotlin: oMap = oArray.toList().groupingBy{it}.eachCount() [note: preserves order] PHP: $oMap = array_count_values($oArray) [note: preserves order] Python: ___ [can use: for vValue in oList: oDict[vValue] = oDict.get(vValue, 0) + 1] [beforehand: oDict = dict()] [note: preserves order] [note: collections.Counter() doesn't preserve order] [requires: import collections] R: table [e.g. oTable = table(oVec)] [note: oKeys = names(oTable)] [note: oValues = unname(oTable)] [WARNING: doesn't preserve order] [WARNING: stores items as strings (and counts as ints)] Ruby: ___ [can use: oMap = oArray.each_with_object(Hash.new(0)){|v,o| o[v]+=1}] [note: Hash.new(0) creates a map with default value 0] Rust: ___ [can use: oMap = oArray.into_iter().fold(BTreeMap::new(), |mut a,v| {a.entry(v).and_modify(|c| *c+=1).or_insert(1); a})] [note: also works with vectors] [requires: use std::collections::BTreeMap] [note: copied(), clone() also works] Scala: ___ [can use: oMap = oArray.groupBy(identity).view.mapValues(_.size).toMap] [note: also works with lists] [WARNING (all): groupBy doesn't preserve order] [e.g. preserve order: var oMap = scala.collection.mutable.LinkedHashMap[String,Int](); oArray.foreach(v=>oMap(oFunc(v))=oMap.getOrElse(oFunc(v), 0)+1)] SQL (MySQL): ___ [e.g. SELECT COUNT(*),v FROM MyTable GROUP BY v ORDER BY min(k)] [e.g. (sorted by frequency): SELECT COUNT(*),v FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC,min(k)] [e.g. (frequency of first char): SELECT COUNT(*),substr(v,1,1) FROM MyTable GROUP BY substr(v,1,1) ORDER BY min(k)] [WARNING: 'GROUP BY' returns 1 row per group] SQL (PostgreSQL): ___ [e.g. SELECT COUNT(*),v FROM MyTable GROUP BY v ORDER BY min(k)] [e.g. (sorted by frequency): SELECT COUNT(*),v FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC,min(k)] [e.g. (frequency of first char): SELECT COUNT(*),substr(v,1,1) FROM MyTable GROUP BY substr(v,1,1) ORDER BY min(k)] [WARNING: 'GROUP BY' returns 1 row per group] [also: SELECT COUNT(v),v FROM unnest(MyArray) v GROUP BY v;] SQL (SQLite): ___ [e.g. SELECT COUNT(*),v FROM MyTable GROUP BY v ORDER BY min(k)] [e.g. (sorted by frequency): SELECT COUNT(*),v FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC,min(k)] [e.g. (frequency of first char): SELECT COUNT(*),substr(v,1,1) FROM MyTable GROUP BY substr(v,1,1) ORDER BY min(k)] [WARNING: 'GROUP BY' returns 1 row per group] Swift: ___ [can use: oDict = oArray.reduce(into:[:]){$0[$1,default:0]+=1}] [WARNING: doesn't preserve order] UFL: Array.Max [comparing values according to the array's type, else numerically, return the max][WARNING: if an array is empty, max typically throws][see also: Max] AutoHotkey: vMax := Max(oArray*) [note: throws if empty array] C++: auto vMax = *std::max_element(std::begin(oArray), std::end(oArray)) [also: auto vMax = *std::max_element(oVec.begin(), oVec.end())] [note: std::begin throws if empty array] [WARNING: reads whatever is it at address if empty vector] [requires (max_element): #include <algorithm>] C#: vMax = oArray.Max() [note: throws if empty array] [requires (Max): using System.Linq] Crystal: vMax = oArray.max [note: throws if empty array] Excel: ___ [can use: MAX()] Excel VBA: vMax = WorksheetFunction.Max(oArray) [note: throws if empty array] Go: vMax := slices.Max(oSlice) [note: throws if empty array] Java: ___ [e.g. int[]: int vMax = Arrays.stream(oArray).max().getAsInt()] [e.g. String[]: var vMax = Arrays.stream(oArray).sorted().skip(oArray.length-1).findFirst().get()] [e.g. List<Integer>/List<String>: var vMax = Collections.max(oList)] [e.g. int[]: int vMax = Arrays.stream(oArray).summaryStatistics().getMax()] [note: max() throws if empty array] JavaScript: vMax = Math.max(...oArray) [note: returns -Infinity if empty array] Kotlin: vMax = oArray.max() [note: throws if empty array] [also: oMaxOpt = oArray.maxOrNull()] PHP: $vMax = max($oArray) [note: 'standard comparison rules' e.g. 'a non-numeric string will be compared to an int as though it were 0'] Python: vMax = max(oList) [note: throws if empty array] R: vMax = max(oVec) [note: returns -Inf if empty array] Ruby: vMax = oArray.max [note: returns nil if empty array] Rust: vMax = oArray.iter().max().unwrap() [note: also works with vectors] Scala: vMax = oArray.max [note: max() throws if empty array] [note: also works with lists] SQL (MySQL): SELECT max(v) FROM MyTable [also: SELECT k,v FROM MyTable WHERE v=(SELECT max(v) FROM MyTable)] SQL (PostgreSQL): SELECT max(v) FROM MyTable [also: SELECT k,v FROM MyTable WHERE v=(SELECT max(v) FROM MyTable)] [also: SELECT max(MyArray)] SQL (SQLite): SELECT max(v) FROM MyTable [also: SELECT k,v FROM MyTable WHERE v=(SELECT max(v) FROM MyTable)] [also: SELECT k,max(v) FROM MyTable] Swift: vMax = oArray.max()! [note: returns nil if empty array] UFL: Array.Min [comparing values according to the array's type, else numerically, return the min][WARNING: if an array is empty, min typically throws][see also: Min] AutoHotkey: vMin := Min(oArray*) [note: throws if empty array] C++: auto vMin = *std::min_element(std::begin(oArray), std::end(oArray)) [also: auto vMin = *std::min_element(oVec.begin(), oVec.end())] [note: std::begin throws if empty array] [WARNING: reads whatever is it at address if empty vector] [requires (min_element): #include <algorithm>] C#: vMin = oArray.Min() [note: throws if empty array] [requires (Min): using System.Linq] Crystal: vMin = oArray.min [note: throws if empty array] Excel: ___ [can use: MIN()] Excel VBA: vMin = WorksheetFunction.Min(oArray) [note: throws if empty array] Go: vMin := slices.Min(oSlice) [note: throws if empty array] Java: ___ [e.g. int[]: int vMin = Arrays.stream(oArray).min().getAsInt()] [e.g. String[]: var vMin = Arrays.stream(oArray).sorted().findFirst().get()] [e.g. List<Integer>/List<String>: var vMin = Collections.min(oList)] [e.g. int[]: int vMin = Arrays.stream(oArray).summaryStatistics().getMin()] [note: min() throws if empty array] JavaScript: vMin = Math.min(...oArray) [note: returns Infinity if empty array] Kotlin: vMin = oArray.min() [note: throws if empty array] [also: oMinOpt = oArray.minOrNull()] PHP: $vMin = min($oArray) [note: 'standard comparison rules' e.g. 'a non-numeric string will be compared to an int as though it were 0'] Python: vMin = min(oList) [note: throws if empty array] R: vMin = min(oVec) [note: returns Inf if empty array] Ruby: vMin = oArray.min [note: returns nil if empty array] Rust: vMin = oArray.iter().min().unwrap() [note: also works with vectors] Scala: vMin = oArray.min [note: min() throws if empty array] [note: also works with lists] SQL (MySQL): SELECT min(v) FROM MyTable [also: SELECT k,v FROM MyTable WHERE v=(SELECT min(v) FROM MyTable)] SQL (PostgreSQL): SELECT min(v) FROM MyTable [also: SELECT k,v FROM MyTable WHERE v=(SELECT min(v) FROM MyTable)] [also: SELECT min(MyArray)] SQL (SQLite): SELECT min(v) FROM MyTable [also: SELECT k,v FROM MyTable WHERE v=(SELECT min(v) FROM MyTable)] [also: SELECT k,min(v) FROM MyTable] Swift: vMin = oArray.min()! [note: returns nil if empty array] UFL: (Array.StrMax) [comparing values as strings, return the max][see also: Array.IntToStrArray] AutoHotkey: ___ C++: auto vMax = *std::max_element(std::begin(oArray), std::end(oArray)) [also: auto vMax = *std::max_element(oVec.begin(), oVec.end())] [requires (max_element): #include <algorithm>] C#: vMax = oArray.Select(v=>v.ToString()).Max() [also (if all values strings): var vMax = oArray.Max()] [requires (Max/Select): using System.Linq] Crystal: vMax = oArray.map(&.to_s).max Excel: ___ Excel VBA: ___ Go: ___ [e.g. []string: vMax := slices.Max(oSlice)] Java: ___ [e.g. String[]: var vMax = Arrays.stream(oArray).sorted().skip(oArray.length-1).findFirst().get()] [e.g. List<String>: var vMax = Collections.max(oList)] JavaScript: vMax = oArray.toSorted().pop() Kotlin: vMax = oArray.map{v->v.toString()}.max() [also (if all values strings): vMax = oArray.max()] [also: oArray.maxOrNull()] PHP: $vMax = array_reduce($oArray, function($vText1, $vText2) {return (($vText1 == null) ? $vText2 : (strcmp($vText1, $vText2) >= 0 ? $vText1 : $vText2));}) [also (if all values strings): $vMax = max($oArray)] Python: vMax = max(map(str, oList)) [also (if all values strings): vMax = max(oList)] R: vMax = tail(oVec[order(as.character(oVec))], 1) [note: returns NULL if empty] Ruby: vMax = oArray.map(&:to_s).max Rust: vMax = oArray.iter().map(|v| (*v).to_string()).max().unwrap() [note: also works with vectors] Scala: vMax = oArray.map(_.toString).max [note: also works with lists] SQL (MySQL): ___ [can use (for a string column): SELECT max(v) FROM MyTable] SQL (PostgreSQL): ___ [can use (for a string column): SELECT max(v) FROM MyTable] SQL (SQLite): ___ [can use (for a string column): SELECT max(v) FROM MyTable] Swift: vMax = oArray.map{String($0)}.max()! [also (if all values strings): vMax = oArray.max()!] UFL: (Array.StrMin) [comparing values as strings, return the min][see also: Array.IntToStrArray] AutoHotkey: ___ C++: auto vMin = *std::min_element(std::begin(oArray), std::end(oArray)) [also: auto vMin = *std::min_element(oVec.begin(), oVec.end())] [requires (min_element): #include <algorithm>] C#: vMin = oArray.Select(v=>v.ToString()).Min() [also (if all values strings): var vMin = oArray.Min()] [requires (Min/Select): using System.Linq] Crystal: vMin = oArray.map(&.to_s).min Excel: ___ Excel VBA: ___ Go: ___ [e.g. []string: vMin := slices.Min(oSlice)] Java: ___ [e.g. String[]: var vMin = Arrays.stream(oArray).sorted().findFirst().get()] [e.g. List<String>: var vMin = Collections.min(oList)] JavaScript: vMin = oArray.toSorted()[0] Kotlin: vMin = oArray.map{v->v.toString()}.min() [also (if all values strings): vMin = oArray.min()] [also: oArray.minOrNull()] PHP: $vMin = array_reduce($oArray, function($vText1, $vText2) {return (($vText1 == null) ? $vText2 : (strcmp($vText1, $vText2) <= 0 ? $vText1 : $vText2));}) [also (if all values strings): $vMin = min($oArray)] Python: vMin = min(map(str, oList)) [also (if all values strings): vMin = min(oList)] R: vMin = head(oVec[order(as.character(oVec))], 1) [also: vMin = oVec[order(as.character(oVec))][1]] [note (both): returns NULL if empty] Ruby: vMin = oArray.map(&:to_s).min Rust: vMin = oArray.iter().map(|v| (*v).to_string()).min().unwrap() [note: also works with vectors] Scala: vMin = oArray.map(_.toString).min [note: also works with lists] SQL (MySQL): ___ [can use (for a string column): SELECT min(v) FROM MyTable] SQL (PostgreSQL): ___ [can use (for a string column): SELECT min(v) FROM MyTable] SQL (SQLite): ___ [can use (for a string column): SELECT min(v) FROM MyTable] Swift: vMin = oArray.map{String($0)}.min()! [also (if all values strings): vMin = oArray.min()!] UFL: Array.Sum [WARNING: negative zero: [-0.0].sum() should return 0.0 to match most programming languages][see also: Sum/Range.Sum/Triang] AutoHotkey: ___ C++: int vSum = std::accumulate(std::begin(oArray), std::end(oArray), 0) [requires (accumulate): #include <numeric>] C#: vSum = oArray.Sum() [requires (Sum): using System.Linq] Crystal: vSum = oArray.sum Excel: ___ [can use: SUM()] [WARNING: returns -0.0, not 0.0: =SUM(MyNZ())] Excel VBA: vSum = WorksheetFunction.Sum(oArray) [WARNING: returns -0.0, not 0.0: WorksheetFunction.Sum(Array(-0#))] Go: ___ Java: vSum = Arrays.stream(oArray).sum() [requires (Arrays): import java.util.*] JavaScript: vSum = oArray.reduce((a,v)=>a+v, 0) [note: negative zero: use seed 0 so that [-0.0].sum() returns 0.0 not -0.0, like most programming languages] Kotlin: vSum = oArray.sum() PHP: $vSum = array_sum($oArray) Python: vSum = sum(oList) R: vSum = sum(oVec) Ruby: vSum = oArray.sum Rust: vSum: i32 = oArray.iter().sum() [WARNING: returns -0.0, not 0.0: [-0.0].iter().sum::<f64>()] Scala: vSum = oArray.sum [WARNING: returns -0.0, not 0.0: Array(-0.0).sum] SQL (MySQL): SELECT sum(v) FROM MyTable SQL (PostgreSQL): SELECT sum(v) FROM MyTable [also: SELECT sum(v) FROM unnest(MyArray) v] [WARNING: returns -0.0, not 0.0: sum(v) FROM unnest(ARRAY['-0.0'::float]) v] SQL (SQLite): SELECT sum(v) FROM MyTable [also: total(), always returns a float: if no values, or all values are NULL: sum(MyCol) returns NULL, total(MyCol) returns 0.0] Swift: vSum = oArray.reduce(0, +) UFL: Array.Product [see also: Product] AutoHotkey: ___ C++: int vProduct = std::accumulate(std::begin(oArray), std::end(oArray), 1, std::multiplies<int>()) [requires (accumulate): #include <numeric>] C#: vProduct = oArray.Aggregate(1, (a,v)=>a*v) [requires (Aggregate): using System.Linq] Crystal: vProduct = oArray.product Excel: ___ [can use: PRODUCT()] Excel VBA: vProduct = WorksheetFunction.Product(oArray) Go: ___ Java: vProduct = Arrays.stream(oArray).reduce(1, (a,v)->a*v) [requires (Arrays): import java.util.*] JavaScript: vProduct = oArray.reduce((a,v)=>a*v) Kotlin: vProduct = oArray.reduce(Int::times) PHP: $vProduct = array_product($oArray) Python: vProduct = math.prod(oList) [requires: import math] R: vProduct = prod(oVec) Ruby: vProduct = oArray.reduce{|a,v| a*v} Rust: vProduct: i32 = oArray.iter().product() Scala: vProduct = oArray.product [FIXME] SQL (MySQL): ___ [can use (for tables, for all positive values): SELECT exp(sum(ln(MyCol))) FROM MyTable] [WARNING: the exp/sum/ln approach loses accuracy] [note: exp(ln(x)) = x] [note: exp(ln(a)+ln(b)) = a*b] [FIXME] SQL (PostgreSQL): ___ [can use (for tables, for all positive values): SELECT exp(sum(ln(MyCol))) FROM MyTable] [WARNING: the exp/sum/ln approach loses accuracy] [note: exp(ln(x)) = x] [note: exp(ln(a)+ln(b)) = a*b] SQL (SQLite): ___ [can use (for tables, for all positive values): SELECT exp(sum(ln(MyCol))) FROM MyTable] [WARNING: the exp/sum/ln approach loses accuracy] [note: exp(ln(x)) = x] [note: exp(ln(a)+ln(b)) = a*b] Swift: vProduct = oArray.reduce(1, *) UFL: Array.Mean [or Array.Average][see also: Mean/Array.Sum] AutoHotkey: ___ C++: double vMean = (double)std::accumulate(std::begin(oArray), std::end(oArray), 0) / (sizeof(oArray)/sizeof(oArray[0])) [requires (accumulate): #include <numeric>] C#: vMean = oArray.Average() [requires (Average): using System.Linq] Crystal: vMean = oArray.sum / oArray.size Excel: ___ [can use: AVERAGE()] Excel VBA: vMean = WorksheetFunction.Average(oArray) Go: ___ Java: vMean = Arrays.stream(oArray).average().orElseThrow() [note: orElseThrow() to unwrap optional value] [also: double vMean = Arrays.stream(oArray).summaryStatistics().getAverage()] [requires (Arrays): import java.util.*] JavaScript: vMean = oArray.reduce((a,v)=>a+v) / oArray.length Kotlin: vMean = oArray.average() PHP: $vMean = array_sum($oArray) / count($oArray) Python: vMean = statistics.mean(oList) [requires: import statistics] R: vMean = mean(oVec) Ruby: vMean = oArray.sum / oArray.length.to_f Rust: vMean = oArray.iter().sum::<i32>() as f32 / oArray.len() as f32 Scala: vMean = oArray.sum/oArray.length.toDouble [FIXME] SQL (MySQL): SELECT avg(v) FROM MyTable [FIXME] SQL (PostgreSQL): SELECT avg(v) FROM MyTable [also: SELECT avg(v) FROM unnest(MyArray) v] SQL (SQLite): SELECT avg(v) FROM MyTable Swift: vMean = oArray.reduce(0, +) / oArray.count UFL: Array.Median [see also: Median/Array.Sort] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ [can use: MEDIAN()] Excel VBA: vMedian = WorksheetFunction.Median(oArray) Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: vMedian = statistics.median(oList) [requires: import statistics] R: vMedian = median(oVec) Ruby: ___ Rust: ___ Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Array.Mode [or Array.Modes][return an array containing the mode(s)][note: if all elements appear once, could either return all elements or throw][see also: Mode/Array.FreqCount] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ [can use: MODE.MULT()] [WARNING: MODE(): returns one mode (even if there are multiple modes), fails if the mode has frequency 1] [version: Excel 2010: MODE.MULT()] Excel VBA: ___ [can use: WorksheetFunction.Mode_Mult()] [WARNING: WorksheetFunction.Mode(): requires an array, returns one mode (even if there are multiple modes), throws if the mode has frequency 1] [e.g. vMode = WorksheetFunction.Mode(oArray)] [version: Excel 2010: MODE.MULT()] Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: oMode = statistics.multimode(oList) [requires: import statistics] R: ___ [WARNING: mode() returns the variable's 'mode', somewhat like typeof()/class()] [can use: modes, any type, excludes NAs: oVecNew = names(table(oVec))[table(oVec)==max(table(oVec))]] [also: modes, ints only, includes NAs: oUnique = unique(oVec); oTable = tabulate(match(oVec, oUnique)); oVecNew = oUnique[oTable == max(oTable)]] [also: one mode only, any type, excludes NAs: vMode = names(which.max(table(oVec)))] Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ [e.g. modes: SELECT COUNT(*),v FROM MyTable GROUP BY v HAVING COUNT(*)=(SELECT COUNT(*) FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC LIMIT 1) ORDER BY COUNT(*) DESC] [e.g. modes (uses temporary variables to avoid repetition): WITH oTemp AS (SELECT COUNT(*) AS vMax,v FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC) SELECT vMax,v FROM oTemp WHERE (SELECT max(vMax) FROM oTemp)=vMax] SQL (PostgreSQL): ___ [e.g. modes: SELECT COUNT(*),v FROM MyTable GROUP BY v HAVING COUNT(*)=(SELECT COUNT(*) FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC LIMIT 1) ORDER BY COUNT(*) DESC] [e.g. modes (uses temporary variables to avoid repetition): WITH oTemp AS (SELECT COUNT(*) AS vMax,v FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC) SELECT vMax,v FROM oTemp WHERE (SELECT max(vMax) FROM oTemp)=vMax] SQL (SQLite): ___ [e.g. modes: SELECT COUNT(*),v FROM MyTable GROUP BY v HAVING COUNT(*)==(SELECT COUNT(*) FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC LIMIT 1) ORDER BY COUNT(*) DESC] [note: 'LIMIT 1' can be omitted] [e.g. modes (uses temporary variables to avoid repetition): WITH oTemp AS (SELECT COUNT(*) AS vMax,v FROM MyTable GROUP BY v ORDER BY COUNT(*) DESC) SELECT vMax,v FROM oTemp WHERE (SELECT max(vMax) FROM oTemp)==vMax] Swift: ___ UFL: Array.Equals [or Array.Match][do the contents of 2 arrays match (same items, same order, same item frequency)] AutoHotkey: ___ C++: auto vIsMatch = std::equal(std::begin(oArray1), std::end(oArray1), std::begin(oArray2)) [also: auto vIsMatch = std::equal(oVec1.begin(), oVec1.end(), oVec2.begin())] [requires (equal): #include <algorithm>] C#: bool vIsMatch = Enumerable.SequenceEqual(oArray1, oArray2) [also: bool vIsMatch = oArray1.SequenceEqual(oArray2)] [requires (Enumerable/SequenceEqual): using System.Linq] Crystal: vIsMatch = (oArray1 == oArray2) Excel: ___ Excel VBA: ___ Go: vIsMatch := slices.Equal(oSlice1, oSlice2) Java: vIsMatch = Arrays.equals(oArray1, oArray2) [e.g. works on int[]/String[]] [requires (Arrays): import java.util.*] JavaScript: ___ [can use: vIsMatch = (oArray1.length == oArray2.length) && [...oArray1.keys()].every(k=>(k in oArray2) && (oArray1[k] === oArray2[k]))] [also: vIsMatch = (JSON.stringify(oArray1) == JSON.stringify(oArray2))] Kotlin: vIsMatch = (oArray1 contentEquals oArray2) PHP: $vIsMatch = ($oArray1 === $oArray2) [note: == compares contents, === compares contents (stricter), neither compare references] Python: vIsMatch = (oList1 == oList2) R: vIsMatch = identical(oVec1, oVec2) Ruby: vIsMatch = (oArray1 == oArray2) Rust: vIsMatch = (oArray1 == oArray2) [also: vIsMatch = oArray1.eq(&oArray2)] [note: also works with vectors] [note: array comparisons (== and eq) fail at compile time if array sizes differ] Scala: vIsMatch = oArray1 sameElements oArray2 SQL (MySQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND 0 = (SELECT COUNT(*) FROM (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) oTemp1) AND 0 = (SELECT COUNT(*) FROM (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) oTemp2) [algorithm: the row counts match, and there are no rows unique to table 1, or table 2] [MAJOR WARNING: in MySQL, 'EXISTS' must be part of 'WHERE (NOT) EXISTS', unlike PostgreSQL/SQLite] [version: MySQL 8.0.31: EXCEPT added] SQL (PostgreSQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) [algorithm: the row counts match, and there are no rows unique to table 1, or table 2] [also: MyArray1 = MyArray2] SQL (SQLite): SELECT (SELECT COUNT(*) FROM MyTable1) == (SELECT COUNT(*) FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) [algorithm: the row counts match, and there are no rows unique to table 1, or table 2] Swift: vIsMatch = (oArray1 == oArray2) UFL: Array.EqualsIgnoreOrder [do the contents of 2 arrays match (same items, key order irrelevant, same item frequency)][WARNING: some algorithms convert arrays to sets, and compare sets, but this removes duplicates, e.g. [1,1,2] and [1,2,2] would be incorrectly considered equal][note: arrays can contain items multiple times, sets only contain items once][see also: Array.Length/Array.Sorted/Array.Sort/Array.Clone] AutoHotkey: ___ C++: ___ [can use: std::vector<std::string> oVecCopy1(std::begin(oArray1), std::end(oArray1)); std::vector<std::string> oVecCopy2(std::begin(oArray2), std::end(oArray2)); std::sort(std::begin(oVecCopy1), std::end(oVecCopy1)); std::sort(std::begin(oVecCopy2), std::end(oVecCopy2)); vIsMatch = std::equal(std::begin(oVecCopy1), std::end(oVecCopy1), std::begin(oVecCopy2), std::end(oVecCopy2));] [requires (equal/sort): #include <algorithm>] [requires: #include <vector>] [beforehand (compare array lengths): vIsMatchLen = (std::end(oArray1)-std::begin(oArray1) == std::end(oArray2)-std::begin(oArray2))] C#: bool vIsMatch = (oArray1.Length == oArray2.Length) && Enumerable.SequenceEqual(oArray1.OrderBy(v=>v), oArray2.OrderBy(v=>v)) [also: bool vIsMatch = (oArray1.Length == oArray2.Length) && oArray1.OrderBy(v=>v).SequenceEqual(oArray2.OrderBy(v=>v))] [requires (Enumerable/SequenceEqual): using System.Linq] Crystal: vIsMatch = (oArray1.size == oArray2.size) && (oArray1.sort == oArray2.sort) Excel: ___ Excel VBA: ___ Go: ___ [can use: oSliceCopy1 := slices.Clone(oSlice1); oSliceCopy2 := slices.Clone(oSlice2); slices.Sort(oSliceCopy1); slices.Sort(oSliceCopy2); vIsMatch := (len(oSlice1) == len(oSlice2)) && slices.Equal(oSliceCopy1, oSliceCopy2)] Java: ___ [can use (e.g. int[]/String[]): var oArrayCopy1 = oArray1.clone(); var oArrayCopy2 = oArray2.clone(); Arrays.sort(oArrayCopy1); Arrays.sort(oArrayCopy2); var vIsMatch = Arrays.equals(oArrayCopy1, oArrayCopy2)] [beforehand (compare array lengths): vIsMatchLen = (oArray1.length == oArray2.length)] JavaScript: ___ [can use: oArrayCopy1 = oArray1.toSorted(); oArrayCopy2 = oArray2.toSorted(); vIsMatch = (oArray1.length == oArray2.length) && [...oArrayCopy1.keys()].every(k=>(k in oArrayCopy2) && (oArrayCopy1[k] === oArrayCopy2[k]))] Kotlin: vIsMatch = (oArray1.size == oArray2.size) && (oArray1.sorted() == oArray2.sorted()) [note: sorted() returns a list] [also: vIsMatch = (oArray1.size == oArray2.size) && (oArray1.sorted().toTypedArray() contentEquals oArray2.sorted().toTypedArray())] PHP: ___ [can use: $oArrayCopy1 = $oArray1; $oArrayCopy2 = $oArray2; sort($oArrayCopy1); sort($oArrayCopy2); $vIsMatch = (count($oArray1) == count($oArray2)) && ($oArrayCopy1 === $oArrayCopy2);] Python: ___ [can use: vIsMatch = (len(oList1) == len(oList2)) and (sorted(oList1) == sorted(oList2))] R: vIsMatch = (length(oVec1) == length(oVec2)) && identical(sort(oVec1), sort(oVec2)) Ruby: vIsMatch = (oArray1.length == oArray2.length) && (oArray1.sort == oArray2.sort) Rust: ___ [can use: let mut oArrayCopy1 = oArray1.clone(); let mut oArrayCopy2 = oArray2.clone(); oArrayCopy1.sort(); oArrayCopy2.sort(); let mut vIsMatch = (oArray1.len() == oArray2.len()) && (oArrayCopy1 == oArrayCopy2);] [also: let mut oArrayCopy1 = oArray1.clone(); let mut oArrayCopy2 = oArray2.clone(); oArrayCopy1.sort(); oArrayCopy2.sort(); let mut vIsMatch = (oArray1.len() == oArray2.len()) && oArrayCopy1.eq(&oArrayCopy2);] [note: also works with vectors] Scala: vIsMatch = (oArray1.length == oArray2.length) && (oArray1.sorted sameElements oArray2.sorted) SQL (MySQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND (SELECT group_concat(v ORDER BY v SEPARATOR x'01') FROM MyTable1) = (SELECT group_concat(v ORDER BY v SEPARATOR x'01') FROM MyTable2) [algorithm: for each table, sort, and concatenate with a rarely used char, compare strings] [MAJOR WARNING: this does not sort: SELECT group_concat(v SEPARATOR x'01') FROM (SELECT v FROM MyTable1 ORDER BY v) oTemp] SQL (PostgreSQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND (SELECT string_agg(v, chr(1)) FROM (SELECT v FROM MyTable1 ORDER BY v) oTemp) = (SELECT string_agg(v, chr(1)) FROM (SELECT v FROM MyTable2 ORDER BY v) oTemp) [algorithm: for each table, sort, and concatenate with a rarely used char, compare strings] [also: array_sort(MyArray1) = array_sort(MyArray2)] SQL (SQLite): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND (SELECT group_concat(v, char(1)) FROM (SELECT v FROM MyTable1 ORDER BY v)) == (SELECT group_concat(v, char(1)) FROM (SELECT v FROM MyTable2 ORDER BY v)) [algorithm: for each table, sort, and concatenate with a rarely used char, compare strings] [MAJOR WARNING: this does not sort: SELECT group_concat(v) FROM MyTable1 ORDER BY v] Swift: vIsMatch = (oArray1.count == oArray2.count) && (oArray1.sorted() == oArray2.sorted()) UFL: Array.EqualsRef [referential equality][do 2 variables point to the same object?][note: arrays are often a special case: e.g. '=' clones and '==' compares values, usually for objects: '=' creates a reference and '==' compares references][see also: OpEquals/Array.Clone/Any.CopyRef/Any.Address/Array.Equals] AutoHotkey: vIsMatch := (oArray1 == oArray2) C++: vIsMatch = (+oArray1 == +oArray2) [note: 'to compare array addresses, use unary '+' to decay operands to pointers'] [also: vIsMatch = (&oArray1 == &oArray2)] C#: vIsMatch = (oArray1 == oArray2) Crystal: vIsMatch = oArray1.same?(oArray2) [also: vIsMatch = (oArray1.object_id == oArray2.object_id)] Excel: ___ Excel VBA: ___ [WARNING: 'oArrayNew = oArray' creates a copy, not a reference] Go: ___ [can use: vIsMatch := (len(oSlice1) == len(oSlice2)) && (unsafe.SliceData(oSlice1) == unsafe.SliceData(oSlice2))] [MAJOR WARNING: 'oArrayNew := oArray' clones, 'oSliceNew := oSlice' creates a reference] Java: vIsMatch = (oArray1 == oArray2) JavaScript: vIsMatch = (oArray1 == oArray2) [also: vIsMatch = (oArray1 === oArray2)] Kotlin: vIsMatch = (oArray1 === oArray2) [also: vIsMatch = (oArray1 == oArray2)] [WARNING: == compares contents for most types, arrays are an exception] [note: === compares references for all types, including arrays] PHP: ___ [can use: $oRefs = [&$oArray1, &$oArray2]; $vIsMatch = ReflectionReference::fromArrayElement($oRefs, 0)->getId() === ReflectionReference::fromArrayElement($oRefs, 1)->getId();] [WARNING: '$oArrayNew = $oArray' creates a copy, not a reference] Python: vIsMatch = (oArray1 is oArray2) [inverse: oArray1 is not oArray2] R: ___ [WARNING: 'oVecNew = oVec' creates a copy, not a reference] Ruby: vIsMatch = oArray1.equal?(oArray2) Rust: ___ [WARNING: 'oArrayNew = oArray' creates a copy, not a reference] Scala: vIsMatch = (oArray1 eq oArray2) [inverse: oArray1 ne oArray2] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [WARNING: 'oArrayNew = oArray' creates a copy, not a reference] UFL: Array.Map [or Array.MapFuncObject][map values using a function object][see also: Array.ForEach] AutoHotkey: ___ C++: std::transform(std::begin(oArray), std::end(oArray), oArrayNew, oFunc) [also: std::transform(oVec.begin(), oVec.end(), std::back_inserter(oVecNew), oFunc)] [requires (transform): #include <algorithm>] C#: oArrayNew = oArray.Select(oFunc).ToArray() [requires (Select): using System.Linq] Crystal: oArrayNew = oArray.map(&oFunc) Excel: ___ Excel VBA: ___ Go: ___ Java: int[] oArrayNew = Arrays.stream(oArray).boxed().mapToInt(oFunc).toArray() [requires (Arrays): import java.util.*] [also: map()] JavaScript: oArrayNew = oArray.map(oFunc) Kotlin: oArrayNew = oArray.map(oFunc).toTypedArray() PHP: $oArrayNew = array_map($oFunc, $oArray) [WARNING (array_map): param order: func then array, unlike array_reduce()/array_filter()] Python: oListNew = list(map(oFunc, oList)) R: oVecNew = mapply(oFunc, oVec) [also: oVecNew = unlist(Map(oFunc, oVec))] [WARNING: these are equivalent: oVecNew = oVec + 5, oVecNew = mapply(\(v) v+5, oVec)] Ruby: oArrayNew = oArray.map(&oFunc) Rust: ___ [can use: oVecNew = oArray.iter().map(|v| oFunc(*v)).collect::<Vec<_>>()] [note: also works with vectors] [also (array to array): oArrayNew = oArray.map(|v| oFunc(v))] Scala: oArrayNew = oArray.map(oFunc) SQL (MySQL): ___ [e.g. UPDATE MyTable SET v=MyFunc(v)] SQL (PostgreSQL): ___ [e.g. UPDATE MyTable SET v=MyFunc(v)] [also: e.g. array_agg(MyFunc(v)) FROM unnest(MyArray) v] [also: ARRAY(SELECT MyFunc(v) FROM unnest(MyArray) v)] SQL (SQLite): ___ [e.g. UPDATE MyTable SET v=MyFunc(v)] Swift: oArrayNew = oArray.map(oFunc) [also (return non-nil results only): oArray.compactMap(oFunc)] [deprecated: oArray.flatMap()] UFL: Array.MapBlock [map values using a function object within a block] AutoHotkey: ___ C++: std::transform(oVec.begin(), oVec.end(), std::back_inserter(oVecNew), [&oFunc](int v) {return oFunc(v);}) [also: std::transform(std::begin(oArray), std::end(oArray), oArrayNew, [&oFunc](int v) {return oFunc(v);})] [note: can replace '[&oFunc]' with '[oFunc]'] [requires (transform): #include <algorithm>] C#: oArrayNew = oArray.Select(v=>oFunc(v)).ToArray() [requires (Select): using System.Linq] Crystal: oArrayNew = oArray.map{|v| oFunc.call(v)} Excel: ___ Excel VBA: ___ Go: ___ Java: int[] oArrayNew = Arrays.stream(oArray).boxed().mapToInt(v->oFunc.apply(v)).toArray() [requires (Arrays): import java.util.*] [also: int[][] oArrayNew = Arrays.stream(oArray).mapToObj(v->oFunc.apply(v)).toArray(int[][]::new)] JavaScript: oArrayNew = oArray.map(v=>oFunc(v)) [also: oArrayNew = oArray.map(function (v) {return oFunc(v)})] Kotlin: oArrayNew = oArray.map{oFunc(it)}.toTypedArray() [also: oArrayNew = oArray.map{v->oFunc(v)}.toTypedArray()] PHP: $oArrayNew = array_map(fn($v)=>$oFunc($v), $oArray) [WARNING (array_map): param order: func then array, unlike array_reduce()/array_filter()] Python: oListNew = list(map(lambda v:oFunc(v), oList)) [also: oListNew = [oFunc(v) for v in oList]] R: oVecNew = mapply(\(v) oFunc(v), oVec) [also: oVecNew = unlist(Map(\(v) oFunc(v), oVec))] [WARNING: these are equivalent: oVecNew = oVec + 5, oVecNew = mapply(\(v) v+5, oVec)] Ruby: oArrayNew = oArray.map{|v| oFunc.call(v)} [also: oArrayNew = oArray.map{oFunc.call(_1)}] [also: oArrayNew = oArray.map{oFunc.call(it)}] [version: Ruby 3.4: 'it' (alias for '_1')] Rust: oVecNew = oArray.iter().map(|v| oFunc(*v)).collect::<Vec<_>>() [note: also works with vectors] [also (array to array): oArrayNew = oArray.map(|v| oFunc(v))] Scala: oArrayNew = oArray.map(oFunc(_)) [also: oArrayNew = oArray.map(v=>oFunc(v))] [WARNING: 'subsequent occurrences of underscores denote successive parameters'] [WARNING: '_' sometimes fails if nested, e.g. within a function call (query: no good documentation source available?)] SQL (MySQL): ___ [e.g. UPDATE MyTable SET v=v*2] [e.g. UPDATE MyTable SET v=v||' my suffix'] [requires (||): set sql_mode=PIPES_AS_CONCAT] [also: UPDATE MyTable SET v=concat(v, ' my suffix')] SQL (PostgreSQL): ___ [e.g. UPDATE MyTable SET v=v*2] [e.g. UPDATE MyTable SET v=v||' my suffix'] [also: e.g. array_agg(v*2) FROM unnest(MyArray) v] [also: ARRAY(SELECT v*2 FROM unnest(MyArray) v)] SQL (SQLite): ___ [e.g. UPDATE MyTable SET v=v*2] [e.g. UPDATE MyTable SET v=v||' my suffix'] Swift: oArrayNew = oArray.map{oFunc($0)} [also: oArrayNew = oArray.map{v in oFunc(v)}] UFL: Array.MapWithIndex [or Array.MapWithIndexFuncObject][map keys/values using a function object][e.g. use MyNumConcat/MyNumConcatMod, it returns the key and value concatenated as an int] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<oVec.size(); i++) oVecNew.push_back(oFunc(i, oVec[i]))] [also: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oArrayNew[i] = oFunc(i, oArray[i])] C#: oArrayNew = oArray.Select(oFuncMod).ToArray() [requires (Select): using System.Linq] Crystal: oArrayNew = oArray.each_with_index.map(&oFuncMod).to_a Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: int[] oArrayNew = IntStream.range(0, oArray.length).boxed().mapToInt(i->oFunc.apply(i,oArray[i])).toArray()] JavaScript: oArrayNew = oArray.map(oFuncMod) Kotlin: oArrayNew = oArray.mapIndexed(oFunc).toTypedArray() PHP: $oArrayNew = array_map($oFunc, array_keys($oArray), $oArray) [WARNING (array_map): param order: func then array, unlike array_reduce()/array_filter()] Python: oListNew = list(map(oFunc, range(len(oList)), oList)) R: ___ [can use: oVecNew = mapply(\(e) oFunc(unlist(e)[1],unlist(e)[2]), oEntries)] [beforehand: oEntries = Map(c, 1:length(oVec), oVec)] Ruby: oArrayNew = oArray.map.with_index(&oFuncMod) [also: oArrayNew = oArray.each_with_index.map(&oFuncMod)] Rust: ___ [can use: oVecNew = oArray.iter().enumerate().map(|(k,v)| oFunc(k as i32,*v)).collect::<Vec<_>>()] Scala: oArrayNew = oArray.zipWithIndex.map(oFuncMod) SQL (MySQL): ___ [e.g. UPDATE MyTable SET v=MyFunc(k, v)] SQL (PostgreSQL): ___ [e.g. UPDATE MyTable SET v=MyFunc(k, v)] SQL (SQLite): ___ [e.g. UPDATE MyTable SET v=MyFunc(k, v)] Swift: oArrayNew = oArray.enumerated().map(oFunc) UFL: Array.MapWithIndexBlock [map keys/values using a function object within a block] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<oVec.size(); i++) oVecNew.push_back(oFunc(i, oVec[i]))] [also: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oArrayNew[i] = oFunc(i, oArray[i])] C#: oArrayNew = oArray.Select((v,k)=>oFunc(k,v)).ToArray() [requires (Select): using System.Linq] Crystal: oArrayNew = oArray.each_with_index.map{|v,k| oFunc.call(k,v)}.to_a Excel: ___ Excel VBA: ___ Go: ___ Java: int[] oArrayNew = IntStream.range(0, oArray.length).boxed().mapToInt(i->oFunc.apply(i,oArray[i])).toArray() JavaScript: oArrayNew = oArray.map((v,k)=>oFunc(k,v)) [also: oArrayNew = oArray.map(function (v,k) {return oFunc(k,v)})] Kotlin: oArrayNew = oArray.mapIndexed{k,v->oFunc(k,v)}.toTypedArray() PHP: $oArrayNew = array_map(fn($k,$v)=>$oFunc($k,$v), array_keys($oArray), $oArray) [WARNING (array_map): param order: func then array, unlike array_reduce()/array_filter()] Python: oListNew = list(map(lambda k,v:oFunc(k,v), range(len(oList)), oList)) [also: oListNew = list(map(lambda e:oFunc(e[0],e[1]), enumerate(oList)))] [also: oListNew = [oFunc(k,v) for k,v in enumerate(oList)]] R: oVecNew = mapply(\(e) oFunc(unlist(e)[1],unlist(e)[2]), oEntries) [beforehand: oEntries = Map(c, 1:length(oVec), oVec)] Ruby: oArrayNew = oArray.map.with_index{|v,k| oFunc.call(k,v)} [also: oArrayNew = oArray.each_with_index.map{|v,k| oFunc.call(k,v)}] [also: oArrayNew = oArray.map.with_index{oFunc.call(_2,_1)}] [also: oArrayNew = oArray.each_with_index.map{oFunc.call(_2,_1)}] Rust: oVecNew = oArray.iter().enumerate().map(|(k,v)| oFunc(k as i32,*v)).collect::<Vec<_>>() Scala: oArrayNew = oArray.zipWithIndex.map(e=>oFunc(e._2,e._1)) [WARNING: '(oFunc(_._2,_._1))' won't work, because each '_' refers to a different argument] SQL (MySQL): ___ [e.g. UPDATE MyTable SET v=v||' '||k] [requires (||): set sql_mode=PIPES_AS_CONCAT] [also: UPDATE MyTable SET v=concat(v, ' ', k)] SQL (PostgreSQL): ___ [e.g. UPDATE MyTable SET v=v||' '||k] [also: array_agg(v||' '||k) FROM unnest(ARRAY['a','b','c']) WITH ORDINALITY AS t(v, k)] [also: ARRAY(SELECT v||' '||k FROM unnest(ARRAY['a','b','c']) WITH ORDINALITY AS t(v, k))] SQL (SQLite): ___ [e.g. UPDATE MyTable SET v=v||' '||k] Swift: oArrayNew = oArray.enumerated().map{oFunc($0,$1)} [also: oArrayNew = oArray.enumerated().map{k,v in oFunc(k,v)}] UFL: Array.FlatMap [note: map v. flatmap: map, function outputs a value, the value is appended to the output array, flatmap, function outputs an a temporary array, the array items are appended to the output array (individually, not as an array), the temporary array is discarded][note: map v. flatmap: map appends function output to array (function takes 1 item and returns 1 item), flatmap appends array items in function output to array (function takes 1 item and returns an array)][flatmap: map each item to an array, then flatten by 1 level, e.g. [1,2,3] to [[1,1,1][2,2,2][3,3,3]] to [1,1,1,2,2,2,3,3,3]][see also: Array.Flat/Array.Flattened] AutoHotkey: ___ C++: ___ C#: oArrayNew = oArray.SelectMany(v=>oFunc(v)).ToArray() [also: oArrayNew = oArray.SelectMany(oFunc).ToArray()] [requires (SelectMany): using System.Linq] Crystal: oArrayNew = oArray.flat_map{|v| oFunc.call(v)} [also: oArrayNew = oArray.flat_map(&oFunc)] Excel: ___ Excel VBA: ___ Go: ___ Java: int[] oArrayNew = Arrays.stream(oArray).boxed().flatMapToInt(v->Arrays.stream(oFunc.apply(v))).toArray() [also: flatMap()] JavaScript: oArrayNew = oArray.flatMap(v=>oFunc(v)) [also: oArrayNew = oArray.flatMap(oFunc)] Kotlin: oArrayNew = oArray.flatMap{v->oFunc(v)}.toTypedArray() [also: oArrayNew = oArray.flatMap(oFunc).toTypedArray()] PHP: ___ [can use: $oArrayNew = array_merge(...array_map(fn($v)=>$oFunc($v), $oArray))] [also: $oArrayNew = array_merge(...array_map($oFunc, $oArray))] Python: ___ [can use: oListNew = [v2 for v1 in oList for v2 in oFunc(v1)]] R: ___ [can use: oVecNew = c(mapply(oFunc, oVec))] [also: oVecNew = unlist(Map(oFunc, oVec))] Ruby: oArrayNew = oArray.flat_map{|v| oFunc.call(v)} Rust: oVecNew = oArray.iter().flat_map(|v| oFunc(*v)).collect::<Vec<_>>() [note: also works with vectors] Scala: oArrayNew = oArray.flatMap(oFunc) [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArrayNew = oArray.flatMap{oFunc($0)} [also: oArrayNew = oArray.flatMap(oFunc)] UFL: Array.Reduce [or Array.ReduceNoSeed/Array.Fold/Array.ReduceLeft/Array.FoldLeft/Array.ReduceFuncObject][WARNING: the examples here do not use a seed parameter, see also: Array.ReduceWithSeed][start with a seed value (or the first array value), it becomes the accumulator value, a function is repeatedly passed 2 values: the accumulator and the next array value, the accumulator is then the return value][reduce values using a function object]['reduce left'/'fold left'][note: no seed parameter, use first array value as the seed][note: 'reduce' functions that lack a seed parameter, typically throw or return null, if passed an empty array][e.g. use MyAdd to get a sum, use MyMul to get a product][see also: Array.ReduceWithSeed] AutoHotkey: ___ C++: ___ [can use (workaround since must specify seed): int vRet = std::accumulate(std::begin(oArray)+1, std::end(oArray), oArray[0], oFunc)] [can use: int vRet = std::accumulate(oVec.begin()+1, oVec.end(), oVec[0], oFunc)] [WARNING: std::accumulate() requires a seed value, workaround: use the first array value as the seed, and pass the rest of the array as the array] [requires (accumulate): #include <numeric>] [also: std::reduce()] [also: std::ranges::fold_left()] C#: vRet = oArray.Aggregate(oFunc) [requires (Aggregate): using System.Linq] Crystal: vRet = oArray.reduce(&oFunc) Excel: ___ Excel VBA: ___ Go: ___ Java: int vRet = Arrays.stream(oArray).boxed().reduce(oFunc).orElseThrow() [requires (Arrays): import java.util.*] [note: if array empty and no seed, would throw, so orElseThrow() needed] JavaScript: vRet = oArray.reduce(oFunc) [note: throws if array empty and no seed] Kotlin: vRet = oArray.reduce(oFunc) [note: throws if array empty and no seed] [note: in Kotlin, reduce() doesn't let you specify a seed, fold() does] PHP: ___ [can use (workaround since must specify seed): $vRet = array_reduce(array_slice($oArray, 1), $oFunc, $oArray[0])] [can use (if seed value of null doesn't affect result): $vRet = array_reduce($oArray, $oFunc)] [WARNING: if the seed (initial value) param is omitted, null is used as the seed, in most languages, if no seed is specified, the first array value is used as the seed, (e.g. sum is OK: null+3=3, concat is OK: null . "abc"="abc", product is not OK: it would be 0: null*3=0)] [note: if array empty and seed param omitted, null is returned] Python: vRet = reduce(oFunc, oList) [requires: from functools import reduce] [note: throws if array empty and no seed] R: vRet = Reduce(oFunc, oVec) Ruby: vRet = oArray.reduce(&oFunc) [alias (inject): reduce (i.e. reduce is an alias of inject)] Rust: ___ [can use: vRet = oArray.into_iter().reduce(|a,v| oFunc(a,v)).unwrap()] Scala: vRet = oArray.reduce(oFunc) [also: reduceLeft()] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use (workaround since must specify seed): vRet = oArray.dropFirst().reduce(oArray[0], oFunc)] [WARNING: reduce() requires a seed value, workaround: use the first array value as the seed, and pass the rest of the array as the array] UFL: Array.ReduceBlock [reduce values using a function object within a block] AutoHotkey: ___ C++: ___ [can use (workaround since must specify seed): int vRet = std::accumulate(std::begin(oArray)+1, std::end(oArray), oArray[0], [oFunc](int a,int v){return oFunc(a,v);})] [can use: int vRet = std::accumulate(oVec.begin()+1, oVec.end(), oVec[0], [oFunc](int a,int v){return oFunc(a,v);})] [WARNING: std::accumulate() requires a seed value, workaround: use the first array value as the seed, and pass the rest of the array as the array] [requires (accumulate): #include <numeric>] [also: std::reduce()] [also: std::ranges::fold_left()] C#: vRet = oArray.Aggregate((a,v)=>oFunc(a,v)) [requires (Aggregate): using System.Linq] Crystal: vRet = oArray.reduce{|a,v| oFunc.call(a,v)} Excel: ___ Excel VBA: ___ Go: ___ Java: int vRet = Arrays.stream(oArray).boxed().reduce((a,v)->oFunc.apply(a,v)).orElseThrow() [requires (Arrays): import java.util.*] JavaScript: vRet = oArray.reduce((a,v)=>oFunc(a,v)) [also: vRet = oArray.reduce(function (a,v) {return oFunc(a,v)})] Kotlin: vRet = oArray.reduce{a,v->oFunc(a,v)} PHP: ___ [can use (workaround since must specify seed): $vRet = array_reduce(array_slice($oArray, 1), fn($a,$v)=>$oFunc($a,$v), $oArray[0])] [can use (if seed value of null doesn't affect result): $vRet = array_reduce($oArray, fn($a,$v)=>$oFunc($a,$v))] Python: vRet = reduce(lambda a,v:oFunc(a,v), oList) [requires: from functools import reduce] [also: vRet = oList[0]; [vRet := oFunc(vRet, v) for v in oList[1:]]] R: vRet = Reduce(\(a,v) oFunc(a,v), oVec) Ruby: vRet = oArray.reduce{|a,v| oFunc.call(a,v)} [also: vRet = oArray.reduce{oFunc.call(_1,_2)}] Rust: vRet = oArray.into_iter().reduce(|a,v| oFunc(a,v)).unwrap() Scala: vRet = oArray.reduce((a,v)=>oFunc(a,v)) [also: vRet = oArray.reduce(oFunc(_,_))] [WARNING: 'subsequent occurrences of underscores denote successive parameters'] [WARNING: '_' sometimes fails if nested, e.g. within a function call (query: no good documentation source available?)] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use (workaround since must specify seed): vRet = oArray.dropFirst().reduce(oArray[0]){oFunc($0,$1)}] [also (workaround since must specify seed): vRet = oArray.dropFirst().reduce(oArray[0]){a,v in oFunc(a,v)}] UFL: Array.ReduceWithIndex [or Array.ReduceWithIndexFuncObject][reduce keys/values using a function object][e.g. use MyAccumNumConcat/MyAccumNumConcatMod, it returns the sum of keys and the sum of values, concatenated as an int] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<oVec.size(); i++) vRet = oFunc(vRet, i, oVec[i])] [beforehand: vRet = 0] C#: ___ [can use: vRet = oArray.Select((v,k)=>new Tuple<int,int>(k,v)).Aggregate(0,(a,e)=>oFunc(a,e.Item1,e.Item2))] Crystal: ___ [can use: vRet = oArray.each_with_index.reduce(0){|a,(v,k)| oFunc.call(a,k,v)}] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (int i=0; i<oArray.length; i++) vRet = oFunc.apply(vRet, i, oArray[i])] [beforehand: vRet = 0] JavaScript: vRet = oArray.reduce(oFuncMod, 0) Kotlin: vRet = oArray.foldIndexed(0, oFuncMod) PHP: ___ [can use: foreach ($oArray as $k=>$v) $vRet = $oFunc($vRet, $k, $v)] [beforehand: $vRet = 0] Python: ___ [can use: for k,v in enumerate(oList): vRet = oFunc(vRet,k,v)] [beforehand: vRet = 0] R: ___ [can use: vRet = Reduce(\(a,e) oFunc(a,unlist(e)[1],unlist(e)[2]), oEntries, 0)] [beforehand: oEntries = Map(c, 1:length(oVec), oVec)] Ruby: ___ [can use: vRet = oArray.each_with_index.reduce(0){|a,(v,k)| oFunc.call(a,k,v)}] Rust: ___ [can use: vRet = oArray.into_iter().enumerate().fold(0, |a,(k,v)| oFunc(a, k as i32, v))] Scala: ___ [can use: vRet = oArray.zipWithIndex.foldLeft(0)((a,e)=>oFunc(a, e._2, e._1))] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: for (k,v) in oArray.enumerated() {vRet = oFunc(vRet,k,v)}] [beforehand: vRet = 0] UFL: Array.ReduceWithIndexBlock [reduce keys/values using a function object within a block] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<oVec.size(); i++) vRet = oFunc(vRet, i, oVec[i])] [beforehand: vRet = 0] C#: vRet = oArray.Select((v,k)=>new Tuple<int,int>(k,v)).Aggregate(0,(a,e)=>oFunc(a,e.Item1,e.Item2)) Crystal: vRet = oArray.each_with_index.reduce(0){|a,(v,k)| oFunc.call(a,k,v)} Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (int i=0; i<oArray.length; i++) vRet = oFunc.apply(vRet, i, oArray[i])] [beforehand: vRet = 0] JavaScript: vRet = oArray.reduce((a,v,k)=>oFunc(a,k,v), 0) Kotlin: vRet = oArray.foldIndexed(0){k,a,v->oFunc(a,k,v)} PHP: ___ [can use: foreach ($oArray as $k=>$v) $vRet = $oFunc($vRet, $k, $v)] [beforehand: $vRet = 0] Python: ___ [can use: for k,v in enumerate(oList): vRet = oFunc(vRet,k,v)] [beforehand: vRet = 0] R: vRet = Reduce(\(a,e) oFunc(a,unlist(e)[1],unlist(e)[2]), oEntries, 0) [beforehand: oEntries = Map(c, 1:length(oVec), oVec)] Ruby: vRet = oArray.each_with_index.reduce(0){|a,(v,k)| oFunc.call(a,k,v)} Rust: vRet = oArray.into_iter().enumerate().fold(0, |a,(k,v)| oFunc(a, k as i32, v)) Scala: vRet = oArray.zipWithIndex.foldLeft(0)((a,e)=>oFunc(a, e._2, e._1)) [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: for (k,v) in oArray.enumerated() {vRet = oFunc(vRet,k,v)}] [beforehand: vRet = 0] UFL: Array.ReduceWithSeed [note: in some languages: 'fold' is with seed, 'reduce' is without seed][note: specify seed (init/identity)][note: 'reduce' functions that require specifying a seed parameter, typically return the seed value if passed an empty array][e.g. use MyAdd to get a sum, use MyMul to get a product] AutoHotkey: ___ C++: int vRet = std::accumulate(std::begin(oArray), std::end(oArray), vSeed, oFunc) [also: int vRet = std::accumulate(oVec.begin(), oVec.end(), vSeed, oFunc)] [requires (accumulate): #include <numeric>] [also: std::reduce()] [also: std::ranges::fold_left()] [also: int vRet = std::accumulate(oVec.begin(), oVec.end(), vSeed, [oFunc](int a,int v){return oFunc(a,v);})] C#: vRet = oArray.Aggregate(vSeed, oFunc) Crystal: vRet = oArray.reduce(vSeed, &oFunc) [also: vRet = oArray.reduce(vSeed){|a,v| oFunc.call(a,v)}] Excel: ___ Excel VBA: ___ Go: ___ Java: int vRet = Arrays.stream(oArray).boxed().reduce(vSeed, oFunc) [requires (Arrays): import java.util.*] [note: a seed is specified, so guaranteed at least one value, orElseThrow not needed] JavaScript: vRet = oArray.reduce(oFunc, vSeed) Kotlin: vRet = oArray.fold(vSeed, oFunc) PHP: $vRet = array_reduce($oArray, $oFunc, $vSeed) Python: vRet = reduce(oFunc, oList, vSeed) [requires: from functools import reduce] [also: vRet = vSeed; [vRet := oFunc(vRet, v) for v in oList]] R: vRet = Reduce(oFunc, oVec, vSeed) Ruby: vRet = oArray.reduce(vSeed, &oFunc) [also: vRet = oArray.reduce(vSeed){|a,v| oFunc.call(a,v)}] [alias (inject): reduce (i.e. reduce is an alias of inject)] Rust: vRet = oArray.iter().fold(vSeed, |a,v| oFunc(a,*v)) Scala: vRet = oArray.fold(vSeed)(oFunc) [also: vRet = oArray.fold(vSeed)((v1,v2)=>oFunc(v1,v2))] [also: foldLeft] [note: foldLeft is more permissive regarding which types it accepts] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vRet = oArray.reduce(vSeed, oFunc) [also: vRet = oArray.reduce(vSeed){oFunc($0,$1)}] [note: 'into' can make blocks simpler and more performant: with 'into' you can modify $0 directly each time (the seed/accumulator), without 'into', you have to clone $0, modify it, and return it each time] [e.g. 'into': to array: oArray.reduce(into:[]){$0.append($1+10)}] [e.g. 'into': to dictionary: oArray.reduce(into:[:]){$0[$1]=1}] UFL: Array.ReduceRight [or Array.FoldRight]['reduce right'/'fold right' is equivalent to reduce left but with the array values reversed, and the 2-param function's param order reversed][see also: Array.Reverse/Array.Reversed/Array.Reduce] AutoHotkey: ___ C++: ___ [can use: std::accumulate(), but it requires a seed value] [also: std::reduce()] [also: std::ranges::fold_right()] [note: created a reversed copy of the array, and reduce using a function where there the 2 parameters are reversed] C#: ___ [can use: vRet = oArrayRev.Aggregate((a,v)=>oFunc(v,a))] [note: where oArrayRev is a reversed copy of the array] Crystal: ___ [can use: vRet = oArray.reverse.reduce{|a,v| oFunc.call(v,a)}] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use (e.g. int[]/double[]): Arrays.stream(oArrayRev).boxed().reduce((a,v)->oFunc.apply(v,a)).orElseThrow()] [note: where oArrayRev is a reversed copy of the array] JavaScript: ___ [can use: vRet = oArray.reduceRight((a,v)=>oFunc(v,a))] [MAJOR WARNING: 'reduce right' is a misnomer, the JavaScript method is equivalent to reversing the array and doing reduce left, for true reverse right, also reverse the 2-param function's param order] [note: throws if array empty and no seed] Kotlin: vRet = oArray.reduceRight(oFunc) [note: throws if array empty and no seed] [note: in Kotlin, reduce doesn't let you specify a seed, fold does] PHP: ___ [can use: $oArrayRev = array_reverse($oArray); $vRet = array_reduce(array_slice($oArrayRev, 1), fn($a,$v)=>$oFunc($v,$a), $oArrayRev[0]);] [can use (if seed value of null doesn't affect result): $vRet = array_reduce(array_reverse($oArray), fn($a,$v)=>$oFunc($v,$a))] Python: ___ [can use: vRet = reduce(lambda a,v:oFunc(v,a), reversed(oList))] [requires: from functools import reduce] [also: vRet = oList[-1]; [vRet := oFunc(v, vRet) for v in oList[-2::-1]]] [note: -2 to start from the 2nd-to-last element, -1 to iterate in reverse order] R: ___ [can use: vRet = Reduce(\(a,v) oFunc(v,a), rev(oVec))] Ruby: ___ [can use: vRet = oArray.reverse.reduce{|a,v| oFunc.call(v,a)}] Rust: ___ [can use: vRet = oArray.into_iter().rev().reduce(|a,v| oFunc(v,a)).unwrap()] Scala: vRet = oArray.reduceRight(oFunc) [also: vRet = oArray.reduceRight((v1,v2)=>oFunc(v1,v2))] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: var oArrayRev = Array(oArray.reversed()); var vRet = oArrayRev.dropFirst().reduce(oArrayRev[0]){oFunc($1,$0)}] [WARNING: reduce() requires a seed value, workaround: use the first array value as the seed, and pass the rest of the array as the array] UFL: Array.ReduceRightWithSeed [or Array.FoldRightWithSeed][see also: Array.Reverse/Array.Reversed/Array.ReduceWithSeed] AutoHotkey: ___ C++: int vRet = std::accumulate(std::begin(oArrayRev), std::end(oArrayRev), vSeed, [oFunc](int a,int v){return oFunc(v,a);}) [also: int vRet = std::accumulate(oVecRev.begin(), oVecRev.end(), vSeed, [oFunc](int a,int v){return oFunc(v,a);})] [requires (accumulate): #include <numeric>] [also: std::reduce()] [also: std::ranges::fold_right()] [note: where oArrayRev(/oVecRev) is a reversed copy of the array(/vector)] C#: ___ [can use: vRet = oArrayRev.Aggregate(vSeed, (a,v)=>oFunc(v,a))] [note: where oArrayRev is a reversed copy of the array] Crystal: ___ [can use: vRet = oArray.reverse.reduce(vSeed){|a,v| oFunc.call(v,a)}] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: int vRet = Arrays.stream(oArrayRev).boxed().reduce(vSeed, (a,v)->oFunc.apply(v,a))] [requires (Arrays): import java.util.*] [note: a seed is specified, so guaranteed at least one value, orElseThrow not needed] [note: where oArrayRev is a reversed copy of the array] JavaScript: ___ [can use: vRet = oArray.reduceRight((a,v)=>oFunc(v,a), vSeed)] [MAJOR WARNING: 'reduce right' is a misnomer, the JavaScript method is equivalent to reversing the array and doing reduce left, for true reverse right, also reverse the 2-param function's param order] Kotlin: vRet = oArray.foldRight(vSeed, oFunc) PHP: ___ [can use: $vRet = array_reduce(array_reverse($oArray), fn($a,$v)=>$oFunc($v,$a), $vSeed)] Python: ___ [can use: vRet = reduce(lambda a,v:oFunc(v,a), reversed(oList), vSeed)] [requires: from functools import reduce] [also: vRet = vSeed; [vRet := oFunc(v, vRet) for v in reversed(oList)]] R: ___ [can use: vRet = Reduce(\(a,v) oFunc(v,a), rev(oVec), vSeed)] Ruby: ___ [can use: vRet = oArray.reverse.reduce(vSeed){|a,v| oFunc.call(v,a)}] Rust: ___ [can use: vRet = oArray.iter().rev().fold(vSeed, |a,v| oFunc(*v,a))] Scala: vRet = oArray.foldRight(vSeed)(oFunc) [also: vRet = oArray.foldRight(vSeed)((v1,v2)=>oFunc(v1,v2))] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: vRet = oArray.reversed().reduce(vSeed){oFunc($1,$0)}] UFL: Array.Filter [or Array.FilterFuncObject][create an array containing values that match a predicate][filter values using a function object][e.g. use MyIsDivisibleBy3 to keep only numbers divisible by 3][see also: Array.Count/Array.GroupBy/Array.Partition/Array.Find] AutoHotkey: ___ C++: std::copy_if(oVec.begin(), oVec.end(), std::back_inserter(oVecNew), oFunc) [beforehand: std::vector<int> oVecNew] [requires (copy_if/remove_if): #include <algorithm>] [also: std::remove_if(oVec.begin(), oVec.end(), oFunc)] C#: oArrayNew = oArray.Where(oFunc).ToArray() [requires (Where): using System.Linq] Crystal: oArrayNew = oArray.select(&oFunc) Excel: ___ Excel VBA: ___ [note: can use Filter() to list matches(/non-matches) that are a *substring* of a needle, case-sensitive/case-insensitive (integer values are treated as strings)] Go: ___ Java: int[] oArrayNew = Arrays.stream(oArray).boxed().filter(oFunc).mapToInt(v->v).toArray() [requires (Arrays): import java.util.*] JavaScript: oArrayNew = oArray.filter(oFunc) Kotlin: oArrayNew = oArray.filter(oFunc).toTypedArray() PHP: $oArrayNew = array_values(array_filter($oArray, $oFunc)) [WARNING: array_filter() maintains indexes, use array_values() to reindex an array] Python: oListNew = list(filter(oFunc, oList)) R: oVecNew = Filter(oFunc, oVec) [e.g. (unusual syntax): oVecNew = oVec[oVec%%3 == 0]] [note: Filter() excludes NA values] Ruby: oArrayNew = oArray.select(&oFunc) [alias (select): filter] Rust: ___ [can use: oVecNew = oArray.iter().filter(|v| oFunc(**v)).collect::<Vec<_>>()] Scala: oArrayNew = oArray.filter(oFunc) [FIXME] SQL (MySQL): ___ [e.g. get even keys: SELECT * FROM MyTable WHERE k%2=0] [e.g. case-insensitive (for ASCII chars, A-Za-z): SELECT * FROM MyTable WHERE k='my string' COLLATE NOCASE] [FIXME] SQL (PostgreSQL): ___ [e.g. get even keys: SELECT * FROM MyTable WHERE k%2=0] [e.g. case-insensitive (for ASCII chars, A-Za-z): SELECT * FROM MyTable WHERE k='my string' COLLATE NOCASE] SQL (SQLite): ___ [e.g. get even keys: SELECT * FROM MyTable WHERE k%2==0] [e.g. case-insensitive (for ASCII chars, A-Za-z): SELECT * FROM MyTable WHERE k=='my string' COLLATE NOCASE] Swift: oArrayNew = oArray.filter(oFunc) UFL: Array.FilterBlock [filter values using a function object within a block] AutoHotkey: ___ C++: std::copy_if(oVec.begin(), oVec.end(), std::back_inserter(oVecNew), [oFunc](int v){return oFunc(v);}) [beforehand: std::vector<int> oVecNew] [requires (copy_if): #include <algorithm>] C#: oArrayNew = oArray.Where(v=>oFunc(v)).ToArray() [requires (Where): using System.Linq] Crystal: oArrayNew = oArray.select{|v| oFunc.call(v)} Excel: ___ Excel VBA: ___ Go: ___ Java: oArrayNew = Arrays.stream(oArray).boxed().filter(v->oFunc.test(v)).mapToInt(v->v).toArray() JavaScript: oArrayNew = oArray.filter(v=>oFunc(v)) [also: oArrayNew = oArray.filter(function (v) {return oFunc(v)})] Kotlin: oArrayNew = oArray.filter{v->oFunc(v)}.toTypedArray() [also: oArrayNew = oArray.filter{oFunc(it)}.toTypedArray()] PHP: $oArrayNew = array_values(array_filter($oArray, fn($v)=>$oFunc($v))) Python: oListNew = list(filter(lambda v:oFunc(v), oList)) [also: oListNew = [v for v in oList if oFunc(v)]] R: oVecNew = Filter(\(v) oFunc(v), oVec) [also (unusual syntax): oVecNew = oVec[oFunc(oVec)]] Ruby: oArrayNew = oArray.select{|v| oFunc.call(v)} [also: oArrayNew = oArray.select{oFunc.call(_1)}] [also: oArrayNew = oArray.select{oFunc.call(it)}] [version: Ruby 3.4: 'it' (alias for '_1')] Rust: oVecNew = oArray.iter().filter(|v| oFunc(**v)).collect::<Vec<_>>() Scala: oArrayNew = oArray.filter(oFunc(_)) [also: oArrayNew = oArray.filter(v=>oFunc(v))] [WARNING: 'subsequent occurrences of underscores denote successive parameters'] [WARNING: '_' sometimes fails if nested, e.g. within a function call (query: no good documentation source available?)] [FIXME] SQL (MySQL): ___ [e.g. SELECT * FROM MyTable WHERE v%3=0] [FIXME] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable WHERE v%3=0] [also: e.g. array_agg(v) FILTER (WHERE v%3=0) FROM UNNEST(MyArray) v] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable WHERE v%3==0] Swift: oArrayNew = oArray.filter{oFunc($0)} [also: oArrayNew = oArray.filter{v in oFunc(v)}] UFL: Array.FilterWithIndex [or Array.FilterWithIndexFuncObject][filter keys/values using a function object][note: array to subarray (containing values but not indexes) based on a function (that receives values and indexes)][e.g. use MyAreEqual/MyAreEqualMod to keep only values that are equal to their array index] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<oVec.size(); i++) if (oFunc(i, oVec[i])) oVecNew.push_back(oVec[i])] [beforehand: std::vector<int> oVecNew] C#: oArrayNew = oArray.Where(oFunc).ToArray() Crystal: oArrayNew = oArray.each_with_index.select(&oFuncMod).map{|vk|vk[0]}.to_a Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: oArrayNew = IntStream.range(0, oArray.length).boxed().filter(i->oFunc.test(i,oArray[i])).mapToInt(i->oArray[i]).toArray()] JavaScript: oArrayNew = oArray.filter(oFunc) Kotlin: oArrayNew = oArray.filterIndexed(oFunc).toTypedArray() PHP: $oArrayNew = array_values(array_filter($oArray, $oFunc, ARRAY_FILTER_USE_BOTH)) Python: ___ [can use: oListNew = [v for k,v in enumerate(oList) if oFunc(k,v)]] R: ___ [can use: oVecNew = mapply(\(e) e[2], Filter(\(e) oFunc(unlist(e)[1],unlist(e)[2]), oEntries))] [beforehand: oEntries = Map(c, 1:length(oVec), oVec)] Ruby: oArrayNew = oArray.select.with_index(&oFunc) [also: oArrayNew = oArray.each_with_index.select(&oFunc).map{|vk|vk[0]}] Rust: ___ [can use: oVecNew = oArray.iter().enumerate().filter(|(k,v)| oFunc(*k as i32,**v)).map(|(_,v)| v).collect::<Vec<_>>()] Scala: oArrayNew = oArray.zipWithIndex.filter(oFuncMod).map(_._2) [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArrayNew = oArray.enumerated().filter(oFunc).map{$1} UFL: Array.FilterWithIndexBlock [filter keys/values using a function object within a block][note: array to subarray (containing values but not indexes) based on a function (that receives values and indexes)] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<oVec.size(); i++) if (oFunc(i, oVec[i])) oVecNew.push_back(oVec[i])] [beforehand: std::vector<int> oVecNew] C#: oArrayNew = oArray.Where((v,k)=>oFunc(k,v)).ToArray() Crystal: oArrayNew = oArray.each_with_index.select{|v,k| oFunc.call(k,v)}.map{|vk|vk[0]}.to_a Excel: ___ Excel VBA: ___ Go: ___ Java: oArrayNew = IntStream.range(0, oArray.length).boxed().filter(i->oFunc.test(i,oArray[i])).mapToInt(i->oArray[i]).toArray() JavaScript: oArrayNew = oArray.filter((v,k)=>oFunc(k,v)) Kotlin: oArrayNew = oArray.filterIndexed{k,v->oFunc(k,v)}.toTypedArray() PHP: $oArrayNew = array_values(array_filter($oArray, fn($v,$k)=>$oFunc($k,$v), ARRAY_FILTER_USE_BOTH)) Python: oListNew = list(map(lambda v:v[1], filter(lambda v:oFunc(v[0],v[1]), enumerate(oList)))) [also: oListNew = [v for k,v in enumerate(oList) if oFunc(k,v)]] R: oVecNew = mapply(\(e) e[2], Filter(\(e) oFunc(unlist(e)[1],unlist(e)[2]), oEntries)) [beforehand: oEntries = Map(c, 1:length(oVec), oVec)] Ruby: oArrayNew = oArray.select.with_index{|v,k| oFunc.call(k,v)} [also: oArrayNew = oArray.each_with_index.select{|v,k| oFunc.call(k,v)}.map{|vk|vk[0]}] [also: oArrayNew = oArray.filter_map.with_index{|v,k| v if oFunc.call(k,v)}] Rust: oVecNew = oArray.iter().enumerate().filter(|(k,v)| oFunc(*k as i32,**v)).map(|(_,v)| v).collect::<Vec<_>>() Scala: oArrayNew = oArray.zipWithIndex.filter(e=>oFunc(e._2,e._1)).map(_._2) SQL (MySQL): ___ [e.g. SELECT * FROM MyTable WHERE k%3=0 AND char_length(v)>10] SQL (PostgreSQL): ___ [e.g. SELECT * FROM MyTable WHERE k%3=0 AND length(v)>10] SQL (SQLite): ___ [e.g. SELECT * FROM MyTable WHERE k%3==0 AND length(v)>10] Swift: oArrayNew = oArray.enumerated().filter{oFunc($0,$1)}.map{$1} UFL: (Array.FilterRemoveNull) [or Array.FilterKeepNonNull][clone an array with nulls removed][note: some of these approaches also unwrap optional objects][see also: Array.CountNonNull] AutoHotkey: ___ C++: std::copy_if(oVec.begin(), oVec.end(), std::back_inserter(oVecNew), [&](auto v){return v!=(std::string)NULL;}) [beforehand: std::vector<std::string> oVecNew] [requires (copy_if/remove_if): #include <algorithm>] [also: std::remove_if(oVec.begin(), oVec.end(), oFunc)] C#: oArrayNew = oArray.Where(v=>v!=null).ToArray() [requires (Where): using System.Linq] Crystal: oArrayNew = oArray.compact [also: oArrayNew = oArray.select{|v| v!=nil}] [also: oArrayNew = oArray.reject{|v| v==nil}] Excel: ___ Excel VBA: ___ Go: ___ Java: String[] oArrayNew = Arrays.stream(oArray).filter(Objects::nonNull).toArray(String[]::new) [also: Integer[] oArrayNew = Arrays.stream(oArray).filter(Objects::nonNull).toArray(Integer[]::new)] [requires (Arrays): import java.util.*] JavaScript: oArrayNew = oArray.filter(v=>v!==null && v!==undefined) [WARNING: vVar == null returns true for null *and undefined*] Kotlin: oArrayNew = oArray.filterNotNull().toTypedArray() [also: oArrayNew = oArray.filter{it!=null}.toTypedArray()] PHP: $oArrayNew = array_values(array_filter($oArray, fn($v)=>$v!=null)) [WARNING: array_filter() maintains indexes, use array_values() to reindex an array] [also: $oArrayNew = array_values(array_filter($oArray, fn($v)=>!is_null($v)))] [WARNING: compact() in PHP is used to collect variable names/values into an array] Python: oListNew = [v for v in oList if v is not None] [also: oListNew = list(filter(lambda v:v is not None, oList))] R: oListNew = oList[!sapply(oList, is.null)] [note: vectors can't contain NULL] [also: remove NA values: oVecNew = oVec[!is.na(oVec)]] [also: remove NA values (throws if list contains a NULL): oListNew = oList[!sapply(oList, is.na)]] [also: remove NA values (but adds attributes): oVecNew = na.omit(oVec)] Ruby: oArrayNew = oArray.compact [also: oArrayNew = oArray.select{|v| v!=nil}] [also: oArrayNew = oArray.reject{|v| v==nil}] Rust: oVecNew = oArray.iter().flatten().cloned().collect::<Vec<_>>() [also: oVecNew = oArray.iter().filter(|v| (*v).is_some()).collect::<Vec<_>>()] [note: for an array of Some/None values] Scala: oArrayNew = oArray.filter(_!=null) [FIXME] SQL (MySQL): DELETE FROM MyTable WHERE v IS NULL [FIXME] SQL (PostgreSQL): DELETE FROM MyTable WHERE v IS NULL [also: array_remove(MyArray, NULL)] SQL (SQLite): DELETE FROM MyTable WHERE v IS NULL Swift: oArrayNew = oArray.compactMap{$0} [also: oArrayNew = oArray.filter{$0 != nil}] UFL: Array.FilterGetEveryNth [get every nth key][e.g. get keys 4/8/12/16/20 (1-based), 3/7/11/15/19 (0-based)][see also: Range.NewWithStep/Array.GroupByWithIndex] AutoHotkey: ___ C++: for (int i=0; i<oVec.size(); i++) if (i%vNum == vNum-1) oVecNew.push_back(oVec[i]) C#: oArrayNew = oArray.Where((v,k)=>(k%vNum == vNum-1)).ToArray() Crystal: oArrayNew = oArray.each_with_index.select{|v,k| (k%vNum == vNum-1)}.map{|vk|vk[0]}.to_a Excel: ___ Excel VBA: ___ Go: ___ Java: oArrayNew = IntStream.range(0, oArray.length).boxed().filter(i->(i%vNum == vNum-1)).mapToInt(i->oArray[i]).toArray() JavaScript: oArrayNew = oArray.filter((v,k)=>(k%vNum == vNum-1)) Kotlin: oArrayNew = oArray.filterIndexed{k,_->(k%vNum == vNum-1)}.toTypedArray() PHP: $oArrayNew = array_values(array_filter($oArray, fn($k)=>($k%$vNum == $vNum-1), ARRAY_FILTER_USE_KEY)) [also: $oArrayNew = array_values(array_filter($oArray, fn($v,$k)=>($k%$vNum == $vNum-1), ARRAY_FILTER_USE_BOTH))] Python: oListNew = [v for k,v in enumerate(oList) if (k%vNum == vNum-1)] R: oVecNew = oVec[seq(vNum, length(oVec), vNum)] [also: oVecNew = mapply(\(e) e[2], Filter(\(e) (as.integer(unlist(e)[1]) %% vNum == 0), oEntries))] [beforehand: oEntries = Map(c, 1:length(oVec), oVec)] [note: keys use 1-based indexes] [e.g. oVecNew = oVec[(1:length(oVec))%%3 == 0]] [e.g. oVecNew = oVec[seq_along(oVec)%%3 == 0]] [e.g. oVecNew = oVec[c(F, F, T)]] Ruby: oArrayNew = oArray.select.with_index{|v,k| (k%vNum == vNum-1)} [also: oArrayNew = oArray.each_with_index.select{|v,k| (k%vNum == vNum-1)}.map{|vk|vk[0]}] [also: oArrayNew = oArray.filter_map.with_index{|v,k| v if (k%vNum == vNum-1)}] Rust: oVecNew = oArray.iter().enumerate().filter(|(k,_)| (k%vNum == vNum-1)).map(|(_,v)| v).collect::<Vec<_>>() Scala: oArrayNew = oArray.zipWithIndex.filter(_._2%vNum == vNum-1).map(_._1) [FIXME] SQL (MySQL): SELECT * FROM MyTable WHERE k%MyCount=0 [FIXME] SQL (PostgreSQL): SELECT * FROM MyTable WHERE k%MyCount=0 SQL (SQLite): SELECT * FROM MyTable WHERE k%MyCount==0 Swift: oArrayNew = oArray.enumerated().filter{($0.0%vNum == vNum-1)}.map{$1} UFL: Array.GroupBy [split array to (a map of) subarrays based on a function][note: the map key names are the function output][see also: Array.Filter/Array.Partition] AutoHotkey: ___ C++: for (const auto& vValue : oArray) oMap[oFunc(vValue)].push_back(vValue) [beforehand: std::map<int,std::vector<int>> oMap] [requires: #include <vector>] [requires: #include <map>] [WARNING: if vKey doesn't exist, 'oMap[vKey]' creates a key with the default value, e.g. an empty vector] C#: oDict = oArray.GroupBy(oFunc).ToDictionary(g=>g.Key, g=>g.ToArray()) [requires (GroupBy/ToDictionary): using System.Linq] Crystal: oMap = oArray.group_by(&oFunc) [also: oMap = oArray.group_by{|v| oFunc.call(v)}] [also: oMap = oArray.each_with_object({} of Int32=>Array(Int32)){|v,o| (o[oFunc.call(v)]||=[] of Int32)<<v}] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [e.g. int[] (note: remove 'boxed()' for String[]): var oMap = Arrays.stream(oArray).boxed().collect(Collectors.groupingBy(oFunc))] [also: var oMap = oList.collect(Collectors.groupingBy(oFunc))] [requires (Collectors): import java.util.stream.*] JavaScript: ___ [e.g. (some browsers support): oMap = Map.groupBy(oArray, oFunc)] [e.g. (some browsers support): oObj = Object.groupBy(oArray, oFunc)] [note: Func receives item/index/array] Kotlin: oMap = oArray.groupBy(oFunc) [also: oMap = oArray.groupBy{oFunc(it)}] PHP: ___ [can use: foreach ($oArray as $v) $oMap[$oFunc($v)][] = $v] [WARNING: '$oMap[$vKey][] = $vValue' creates an array if it doesn't exist, and pushes] [beforehand: $oMap = []] Python: for k,g in groupby(oListTemp, oFunc): oDict[k] = list(g) [beforehand: oListTemp = sorted(oList, key=oFunc); oDict = {}] [requires: from itertools import groupby] R: oList = split(oVec, oFunc(oVec)) [e.g. oList = split(oVec, oVec %% 5)] [note: returns a list of lists] Ruby: oMap = oArray.group_by(&oFunc) [also: oMap = oArray.group_by{|v| oFunc.call(v)}] [also: oMap = oArray.each_with_object({}){|v,o| (o[oFunc.call(v)]||=[])<<v}] Rust: oMap: BTreeMap::<_,Vec<_>> = oArray.into_iter().fold(BTreeMap::new(), |mut a,v| {a.entry(oFunc(v)).or_default().push(v); a}) [requires: use std::collections::BTreeMap] [e.g. fn oFunc (vNum:i32) -> i32{vNum%3}] [note: also works with vectors] Scala: oMap = oArray.groupBy(oFunc) [note: returns a map where each key is an array] [note: returns a map where each key is a list: oMapNew = oArray.groupBy(oFunc).view.mapValues(v=>v.toList).toMap] [note (both): also works with lists] [WARNING (all): groupBy doesn't preserve order] [e.g. preserve order: var oMap = scala.collection.mutable.LinkedHashMap[Int,List[Int]]().withDefaultValue(List[Int]()); oArray.foreach(v=>oMap(oFunc(v)):+=v)] SQL (MySQL): ___ [e.g. values grouped by first letter: SELECT substr(v,1,1),group_concat(v ORDER BY k SEPARATOR ',') FROM MyTable GROUP BY substr(v,1,1)] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): ___ [e.g. values grouped by first letter: SELECT substr(v,1,1),string_agg(v, ',' ORDER BY k) FROM MyTable GROUP BY substr(v,1,1)] [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] SQL (SQLite): ___ [e.g. values grouped by first letter: SELECT substr(v,1,1),group_concat(v, ',' ORDER BY k) FROM MyTable GROUP BY substr(v,1,1)] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] Swift: oDict = Dictionary(grouping:oArray, by:oFunc) UFL: Array.GroupByWithIndex [split array to (a map of) subarrays (containing values but not indexes) based on a function (that receives values and indexes)][note: the map key names are the function output][note: workaround to do GroupBy using value *and key* (with index): array to entries (key-value pairs), to map of arrays of entries, to map of arrays of values][see also: Array.Filter/Array.Partition/Array.Entries/Array.FilterGetEveryNth/Array.Chunk/Map.MultiFlip] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oMap[oFunc(i, oArray[i])].push_back(oArray[i]) [beforehand: std::map<int,std::vector<int>> oMap] [requires: #include <vector>] [requires: #include <map>] [WARNING: if vKey doesn't exist, 'oMap[vKey]' creates a key with the default value, e.g. an empty vector] C#: oDict = oArray.Select((v,k)=>new{k=k,v=v}).GroupBy(e=>oFunc(e.k,e.v)).ToDictionary(g=>g.Key, g=>g.Select(e=>e.v).ToArray()) [requires (GroupBy/Select/ToDictionary): using System.Linq] Crystal: oMap = oArray.each_with_index.group_by{|v,k| oFunc.call(k,v)}.map{|k,v| [k,v.map{|v| v[0]}]}.to_h Excel: ___ Excel VBA: ___ Go: ___ Java: var oMap = IntStream.range(0, oArray.length).boxed().collect(Collectors.groupingBy(i->oFunc.apply(i,oArray[i]), Collectors.mapping(i->oArray[i], Collectors.toList()))) [requires (Collectors): import java.util.stream.*] JavaScript: ___ [e.g. (some browsers support): oMap = Map.groupBy(oArray, oFunc)] [e.g. (some browsers support): oObj = Object.groupBy(oArray, oFunc)] [note: Func receives item/index/array] Kotlin: oMap = oArray.withIndex().groupBy({oFunc(it.index,it.value)}, {it.value}) PHP: ___ [can use: foreach ($oArray as $k=>$v) $oMap[$oFunc($k,$v)][] = $v] [WARNING: '$oMap[$vKey][] = $vValue' creates an array if it doesn't exist, and pushes] [beforehand: $oMap = []] Python: ___ [can use: for k,g in groupby(oListTemp, oFunc): oDict[k] = list(map(lambda v : v[1], g))] [beforehand: oListTemp = sorted(enumerate(oList), key=oFunc); oDict = {}] [requires: from itertools import groupby] [note: where Func accepts one param, a key-value pair] R: split(oVec, oFunc(seq_along(oVec), oVec)) [also: split(oVec, unlist(Map(oFunc, seq_along(oVec), oVec)))] [note: where oFunc accepts 2 params (k and v)] Ruby: oArray.group_by.with_index{|v,k| oFunc.call(k,v)} [also: oMap = oArray.each_with_index.group_by{|v,k| oFunc.call(k,v)}.map{|k,v| [k,v.map{|v| v[0]}]}.to_h] Rust: oMap: BTreeMap::<_,Vec<_>> = oArray.into_iter().enumerate().fold(BTreeMap::new(), |mut a,(k,v)| {a.entry(oFunc(k as i32,v)).or_default().push(v); a}) [requires: use std::collections::BTreeMap] [e.g. fn oFunc (vKey:i32, vValue:i32) -> i32{vKey%3}] [note: also works with vectors] Scala: oMap = oArray.zipWithIndex.groupBy(oFunc).view.mapValues(v=>v.map(e=>e._1)).toMap [note: returns a map where each key is an array] [note: returns a map where each key is a list: oMap = oArray.zipWithIndex.groupBy(oFunc).view.mapValues(v=>v.map(e=>e._1).toList).toMap] [note (both): also works with lists] [WARNING (all): groupBy doesn't preserve order] [e.g. preserve order: var oMap = scala.collection.mutable.LinkedHashMap[Int,List[Int]]().withDefaultValue(List[Int]()); oArray.view.zipWithIndex.foreach((v,k)=>oMap(oFunc(k,v)):+=v)] SQL (MySQL): ___ [e.g. values grouped by mod of key: SELECT (k+MyCount-1)%MyCount+1,group_concat(v ORDER BY k SEPARATOR ',') FROM MyTable GROUP BY (k+MyCount-1)%MyCount+1] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): ___ [e.g. values grouped by mod of key: SELECT (k+MyCount-1)%MyCount+1,string_agg(v, ',' ORDER BY k) FROM MyTable GROUP BY (k+MyCount-1)%MyCount+1] [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] SQL (SQLite): ___ [e.g. values grouped by mod of key: SELECT (k+MyCount-1)%MyCount+1,group_concat(v, ',' ORDER BY k) FROM MyTable GROUP BY (k+MyCount-1)%MyCount+1] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] Swift: oDict = Dictionary(grouping:oArray.enumerated(), by:{oFunc($0,$1)}).mapValues{$0.map{$0.element}} UFL: (Array.Partition) [create 2 separate arrays based on a filter (predicate)][note: in some languages, 'partition' rearranges keys within an array (e.g. non-matches then matches)][see also: Array.Filter/Array.GroupBy] AutoHotkey: ___ C++: auto oPivot = std::partition(std::begin(oArray), std::end(oArray), oFunc) [also: auto oPivot = std::partition(oVec.begin(), oVec.end(), oFunc)] [requires: #include <vector>] [requires (partition): #include <algorithm>] [note (array): false value count: vPivot = oPivot - oArray] [note (vector): false value count: vPivot = oPivot - oVec.begin()] C#: oDict = oArray.GroupBy(oFunc).ToDictionary(g=>g.Key, g=>g.ToArray()) [requires (GroupBy/ToDictionary): using System.Linq] Crystal: oTuple = oArray.partition(&oFunc) [also: oTuple = oArray.partition{|v| oFunc.call(v)}] [also: group_by()] Excel: ___ Excel VBA: ___ [note: can use Filter() to list matches(/non-matches) that are a *substring* of a needle, case-sensitive/case-insensitive (integer values are treated as strings)] Go: ___ Java: var oMap = Arrays.stream(oArray).boxed().collect(Collectors.partitioningBy(oFunc)) [also: var oMap = oList.stream().collect(Collectors.partitioningBy(oFunc))] [requires (Collectors): import java.util.stream.*] JavaScript: ___ [e.g. (some browsers support): oMap = Map.groupBy(oArray, oFunc)] [e.g. (some browsers support): oObj = Object.groupBy(oArray, oFunc)] Kotlin: (oArray1, oArray2) = oArray.partition(oFunc) [also: (oArray1, oArray2) = oArray.partition{oFunc(it)}] [also: oMap = oArray.groupBy(oFunc)] PHP: ___ [can use: foreach ($oArray as $vValue) $oMap[$oFunc($vValue)][] = $vValue] [WARNING: '$oMap[$vKey][] = $vValue' creates an array if it doesn't exist, and pushes] [beforehand: $oMap = []] Python: for k,g in groupby(oList, oFunc): oDict[k] = list(g) [beforehand: oList = sorted(oList, key=oFunc)] [beforehand: oDict = {}] [requires: from itertools import groupby] R: oList = split(oVec, oFunc(oVec)) [e.g. oList = split(oVec, oVec %% 3 == 0)] [note: returns a list of lists] Ruby: oArrayNew = oArray.partition(&oFunc) [also: oArrayNew = oArray.partition{|v| oFunc.call(v)}] [also: group_by()] Rust: oMap: BTreeMap::<_,Vec<_>> = oArray.into_iter().fold(BTreeMap::new(), |mut a,v| {a.entry(oFunc(v)).or_default().push(v); a}) [requires: use std::collections::BTreeMap] [e.g. fn oFunc (vNum:i32) -> i32{vNum%2}] [note: also works with vectors] Scala: var (oArrayT, oArrayF) = oArray.partition(oFunc) [also: var oTuple = oArray.partition(oFunc)] [note (both): also works with lists] SQL (MySQL): ___ [e.g. values grouped by mod of key: SELECT k%2,group_concat(v ORDER BY k SEPARATOR ',') FROM MyTable GROUP BY k%2] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): ___ [e.g. values grouped by mod of key: SELECT k%2,string_agg(v, ',' ORDER BY k) FROM MyTable GROUP BY k%2] [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] SQL (SQLite): ___ [e.g. values grouped by mod of key: SELECT k%2,group_concat(v, ',' ORDER BY k) FROM MyTable GROUP BY k%2] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] Swift: vPivot = oArray.partition(by:oFunc) [note: puts non-matches at start (before pivot) and matches at end (including pivot)] [WARNING: unstable sort (items are randomly shuffled)] [e.g. oNonMatch = oArray[..<vPivot].sorted()] [e.g. oMatch = oArray[vPivot...].sorted()] UFL: Array.Chunk [or Array.GroupN][split array to subarrays of n values (last subarray can contain fewer values)][array to array of arrays][note: copy keys rather than create references][see also (inverse): Array.Flat][see also: Array.GroupByWithIndex/Array.SliceTo/StrChunk] AutoHotkey: ___ C++: ___ [can use: for (int i=0; i<oVec.size(); i+=vCount) oVecNew.push_back(std::vector<int>(oVec.begin()+i, oVec.begin()+(i+vCount<oVec.size()?i+vCount:oVec.size())))] [beforehand: std::vector<std::vector<int>> oVecNew] [beforehand: oVecNew.reserve(oVec.size()/vCount+1)] C#: oChunks = oArray.Chunk(vCount).ToArray() Crystal: oChunks = oArray.each_slice(vCount).to_a Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: int[][] oChunks = IntStream.iterate(0, i->i+vCount).limit((long)Math.ceil((double)oArray.length/vCount)).mapToObj(j->Arrays.copyOfRange(oArray, j, Math.min(j+vCount, oArray.length))).toArray(int[][]::new)] [requires (Arrays): import java.util.*] [requires: import java.util.stream.*] [note: also works with strings, just replace 'int[][]' with 'String[][]' twice] JavaScript: ___ [can use: oChunks = Array(Math.ceil(oArray.length/vCount)).fill().map((v,k)=>oArray.slice(k*vCount, k*vCount+vCount))] Kotlin: oChunks = oArray.toList().chunked(vCount) PHP: $oChunks = array_chunk($oArray, $vCount) Python: oChunks = list(itertools.batched(oList, vCount)) [requires: import itertools] [also: oChunks = [oList[i:i+vCount] for i in range(0, len(oList), vCount)]] R: oChunks = split(oVec, ceiling(seq_along(oVec)/vCount)) [note: returns a list of lists] Ruby: oChunks = oArray.each_slice(vCount).to_a Rust: oChunks: Vec<Vec<i32>> = oVec.chunks(vCount).map(|v| v.to_vec()).collect() Scala: oChunks = oArray.grouped(vCount).toArray SQL (MySQL): ___ [e.g. values in chunks of size n: SELECT (k-1) DIV MyCount+1,group_concat(v ORDER BY k SEPARATOR ',') FROM MyTable GROUP BY (k-1) DIV MyCount+1] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): ___ [e.g. values in chunks of size n: SELECT (k-1)/MyCount+1,string_agg(v, ',' ORDER BY k) FROM MyTable GROUP BY (k-1)/MyCount+1] [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] SQL (SQLite): ___ [e.g. values in chunks of size n: SELECT (k-1)/MyCount+1,group_concat(v, ',' ORDER BY k) FROM MyTable GROUP BY (k-1)/MyCount+1] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] Swift: ___ [can use: oChunks = stride(from:0, to:oArray.count, by:vCount).map{Array(oArray[$0..<min($0+vCount, oArray.count)])}] UFL: Array.Zip [combine two arrays (of equal length) into an array of tuples(/arrays/array-like objects), the first tuple contains the first element of each input array][e.g. ["a1","a2","a3"] and ["b1","b2","b3"] to [["a1","b1"], ["a2","b2"], ["a3","b3"]]] AutoHotkey: ___ C++: std::transform(oVec1.begin(), oVec1.end(), oVec2.begin(), std::back_inserter(oVecNew), [](const auto&v1, const auto&v2) {return std::vector<std::string>{v1,v2};}) [note: returns a vector of vectors] [requires (transform): #include <algorithm>] [beforehand: std::vector<std::vector<std::string>> oVecNew] C#: var oArrayNew = oArray1.Zip(oArray2, (v1,v2)=>(v1,v2)).ToArray() [note: returns an array of tuples] [note: Zip() returns an iterator] [requires (Zip): using System.Linq] [also (for an array of arrays): var oArrayNew = oArray1.Zip(oArray2, (v1,v2)=>new String[]{v1,v2}).ToArray()] Crystal: oArrayNew = oArray1.zip(oArray2) [note: returns an array of tuples] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: String[][] oArrayNew = IntStream.range(0, oArray1.length).mapToObj(i->new String[]{oArray1[i],oArray2[i]}).collect(Collectors.toList()).toArray(String[][]::new)] [also (for lists): List<List<String>> oListNew = IntStream.range(0, oArray1.length).mapToObj(i->Arrays.asList(oArray1[i],oArray2[i])).collect(Collectors.toList())] [requires (IntStream/Collectors): import java.util.stream.*] [requires (Arrays): import java.util.*] JavaScript: ___ [can use: oArrayNew = oArray1.map((v,k)=>[v,oArray2[k]])] [note: returns an array of arrays] Kotlin: oArrayNew = oArray1.zip(oArray2).toTypedArray() [note: zip() returns a list of pairs] PHP: $oArrayNew = array_map(null, $oArray1, $oArray2) [note: returns an array of arrays] Python: oListNew = list(zip(oList1, oList2)) [note: returns a list of tuples] R: oListNew = mapply(c, oVec1, oVec2, SIMPLIFY=FALSE, USE.NAMES=FALSE) [also: oListNew = unname(Map(c, oVec1, oVec2))] [also: oListNew = list(); for (v in 1:length(oVec1)) oListNew[[v]] = c(oVec1[v], oVec2[v])] [note: returns a list of vectors] Ruby: oArrayNew = oArray1.zip(oArray2) [note: returns an array of arrays] Rust: oVecNew = oArray1.into_iter().zip(oArray2.into_iter()).collect::<Vec<_>>() [note: returns a vector of tuples] [note: also works with vectors] Scala: oArrayNew = oArray1.zip(oArray2) [note: returns an array of tuples] [note: also works with lists] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArrayNew = zip(oArray1, oArray2) [note: returns a sequence of pairs] [also (for an array of pairs): oArrayNew = zip(oArray1, oArray2).map{[$0,$1]}] [note: for tuples, use '($0,$1)' instead] UFL: Array.ZipMult [combine multiple arrays (of equal length) into an array of tuples(/arrays/array-like objects), the first tuple contains the first element of each input array][e.g. ["a1","a2","a3"] and ["b1","b2","b3"] to [["a1","b1"], ["a2","b2"], ["a3","b3"]]] AutoHotkey: ___ C++: ___ C#: var oArrayNew = oArray1.Zip(oArray2, (v1,v2)=>(v1,v2)).Zip(oArray3, (o,v3)=>(o.v1,o.v2,v3)).ToArray() [requires (Zip): using System.Linq] [also (from 4 arrays): var oArrayNew = oArray1.Zip(oArray2, (v1,v2)=>(v1,v2)).Zip(oArray3, (o,v3)=>(o.v1,o.v2,v3)).Zip(oArray4, (o,v4)=>(o.v1,o.v2,o.v3,v4)).ToArray()] [also (from 4 arrays via map): var oArrayNew = oArray1.Select((v,k)=>(v,oArray2[k],oArray3[k],oArray4[k])).ToArray()] Crystal: oArrayNew = oArray1.zip(oArray2, oArray3) Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: String[][] oArrayNew = IntStream.range(0, oArray1.length).mapToObj(i->new String[]{oArray1[i],oArray2[i],oArray3[i]}).collect(Collectors.toList()).toArray(String[][]::new)] [also (for lists): List<List<String>> oListNew = IntStream.range(0, oArray1.length).mapToObj(i->Arrays.asList(oArray1[i],oArray2[i],oArray3[i])).collect(Collectors.toList())] [requires (IntStream/Collectors): import java.util.stream.*] [requires (Arrays): import java.util.*] JavaScript: ___ [can use: oArrayNew = oArray1.map((v,k)=>[v,oArray2[k],oArray3[k]])] Kotlin: ___ [can use: oArrayNew = oArray1.mapIndexed{k,v->listOf(v,oArray2[k],oArray3[k])}] PHP: $oArrayNew = array_map(null, $oArray1, $oArray2, $oArray3) Python: oListNew = list(zip(oList1, oList2, oList3)) R: oListNew = mapply(c, oVec1, oVec2, oVec3, SIMPLIFY=FALSE, USE.NAMES=FALSE) [also: oListNew = unname(Map(c, oVec1, oVec2, oVec3))] [also: oListNew = list(); for (v in 1:length(oVec1)) oListNew[[v]] = c(oVec1[v], oVec2[v], oVec3[v])] Ruby: oArrayNew = oArray1.zip(oArray2, oArray3) Rust: ___ Scala: oArrayNew = oArray1.lazyZip(oArray2).lazyZip(oArray3).toArray [note: returns an array of tuples] [note: also works with lists] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArrayNew = zip(oArray1, zip(oArray2, oArray3)).map{[$0,$1.0,$1.1]} [note: for tuples, use '($0,$1.0,$1.1)' instead] [also (from 4 arrays): var oArrayNew = zip(oArray1, zip(oArray2, zip(oArray3, oArray4))).map{[$0,$1.0,$1.1.0,$1.1.1]}] [also (from 4 arrays via map): var oArrayNew = oArray1.enumerated().map{[$1,oArray2[$0],oArray3[$0],oArray4[$0]]}] UFL: (Array.SetMultOverwriteMap) [array overwrite/combine/merge, overwrite/add values, based on a map][see also: Map.LoopKeyValue] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ [also (add/overwrite keys based on an array): $oArray1 = array_replace($oArray1, $oArray2, $oArray3)] [note: array_replace() overwrites keys] [WARNING: array_merge() appends index keys (and overwrites keys with string names)] Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [can use: for ((k,v) <- oMap) oArray(k)=v] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.SetMultOverwriteEntries) [array overwrite/combine/merge, overwrite/add values, based on entries (key-value pairs)][e.g. oEntries = [[3,"d"]], contains 1 entry, it would set the value of key 3 to 'd', throwing if the array was too small][see also: Array.LoopValue] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [can use: for ((k,v) <- oEntries) oArray(k)=v] [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.SetMultSkipExistMap) [or Array.SetMultIfAbsent/Array.SetMultNoOverwrite][array combine, add values, if the key doesn't already exist, based on a map (add only, don't overwrite) (maintain original values)] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ [also (add keys based on an array): $oArray1 += $oArray2] [note: assuming 2 arrays that satisfy array_is_list(), $oArray1 would only be modified if $oArray2 was longer ($oArray1 would receive the last keys of $oArray2)] Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.SetMultSkipExistEntries) [or Array.SetMultIfAbsent/Array.SetMultNoOverwrite][array combine, add values, if the key doesn't already exist, based on entries (key-value pairs) (add only, don't overwrite) (maintain original values)][e.g. oEntries = [[3,"d"]], would set the value of key 3 to 'd', if key 3 'didn't exist', throwing if the array was too small] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Array.Default [define the default value returned when an element with no value is requested][see also: Array.GetOrDefault] AutoHotkey: oArray.Default := vValue C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ [note: array of type Variant/Integer/Double/String initialised with Empty/0/0/"" respectively] Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ [can use (create a table with default values): e.g. CREATE TABLE MyTable (k INTEGER, v INTEGER DEFAULT 0)] [e.g. CREATE TABLE MyTable (k INTEGER, v TEXT DEFAULT '')] SQL (PostgreSQL): ___ [can use (create a table with default values): e.g. CREATE TABLE MyTable (k INTEGER, v INTEGER DEFAULT 0)] [e.g. CREATE TABLE MyTable (k INTEGER, v TEXT DEFAULT '')] SQL (SQLite): ___ [can use (create a table with default values): e.g. CREATE TABLE MyTable (k INTEGER, v INTEGER DEFAULT 0) STRICT] [e.g. CREATE TABLE MyTable (k INTEGER, v TEXT DEFAULT '') STRICT] Swift: ___ [can use (to fill in blanks): oArray = oArray.map{$0 ?? vDefault}] UFL: (Array.Next) [generate the next array e.g. [1,2,3] to [1,2,4], e.g. [1,9,9] to [2,0,0]][ideally: specify min/max values for each array item via an object][see also: StrNext] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.Nearest) [return the nearest number: oArray.Nearest(vNum)][e.g. use case: round to the nearest multiple of 5 (an alternative to MRound): [vNum-vNum%5, vNum-vNum%5+5].Nearest(vNum)][note: whether array in ascending/descending order determines whether tiebreaker is below/above needle value][see also: Nearest] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use (note: inefficiently repeats calculations, and doesn't break early if exact match found) (note: tiebreaker: < returns first match, change to <= to return last match): vNearest = oArray.reduce((a,v)=>Math.abs(vNum-v)<Math.abs(vNum-a)?v:a)] Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.ToMap) [or Vector.ToMap][i.e. indexes become key names, values become values][see also: Array.PrintWithIndex/Array.Entries] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oMap[i] = oArray[i] [beforehand: std::map<int,std::string> oMap] C#: var oDict = oArray.Select((v,k)=>new{k,v}).ToDictionary(e=>e.k, e=>e.v) [requires (Select/ToDictionary): using System.Linq] Crystal: oMap = oArray.each_with_index.map{|v,k| [k,v]}.to_h [also: oMap = ((0...oArray.size).zip oArray).to_h] [also: oMap = Hash.zip((0...oArray.size).to_a, oArray)] Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) oMap.put(i, oArray[i]) [beforehand: LinkedHashMap<Integer,String> oMap = new LinkedHashMap<>()] JavaScript: new Map(...[oArray.entries()]) Kotlin: oMap = oArray.mapIndexed{k,v->k to v!!}.toMap() PHP: $oMap = $oArray [note: this creates a copy of the 'array' (the PHP array is a linear and associative array)] [note (to get integer keys only): $oArray = array_filter($oArray, fn($v,$k)=>is_int($k), ARRAY_FILTER_USE_BOTH)] Python: oDict = {k:v for k,v in enumerate(oList)} R: oMap = setNames(oVec, 1:length(oVec)) [also: oMap = setNames(oVec, seq_along(oVec))] [note: setNames param order: values then keys] Ruby: oMap = oArray.map.with_index{|v,k| [k,v]}.to_h [also: oMap = ((0...oArray.length).zip oArray).to_h] Rust: oMap = oArray.iter().enumerate().collect::<BTreeMap<_,_>>() [also: oMap = oVec.clone().into_iter().enumerate().collect::<BTreeMap<_,_>>()] Scala: oMap = oArray.zipWithIndex.map(e=>(e._2,e._1)).toMap [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oDict = Dictionary(uniqueKeysWithValues:oArray.enumerated().map{($0,$1)}) UFL: (Array.ToObject) [i.e. indexes become property names, values become values] AutoHotkey: ___ C++: ___ C#: foreach (var oEntry in oArray.Select((v,k)=>new KeyValuePair<string,object>(k.ToString(),v))) ((IDictionary<string,object>)oObj).Add(oEntry) [requires (KeyValuePair): using System.Collections.Generic] [requires (Select): using System.Linq] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [see also: 'Object.ToMap'/'Object.Set'] JavaScript: oObj = {...oArray} [also: oObj = Object.assign({}, oArray)] Kotlin: ___ PHP: $oObj = (object)$oArray Python: oObj = SimpleNamespace(**{str(k):v for k,v in enumerate(oList)}) R: ___ Ruby: ___ Rust: ___ Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Array.ToSet [or Vector.ToSet][array to set][see also: Array.Distinct/Set.ToArray] AutoHotkey: ___ C++: ___ [can use: int vSize = sizeof(oArray)/sizeof(oArray[0]); std::set<std::string>oSet(oArray, oArray+vSize)] [also (from vector): std::set<std::string>oSet(oVec.begin(), oVec.end())] [requires: #include <set>] C#: oSet = new HashSet<string>(oArray) [requires (HashSet): using System.Collections.Generic] Crystal: oSet = oArray.to_set Excel: ___ Excel VBA: ___ Go: ___ Java: oSet = new LinkedHashSet<String>(Arrays.asList(oArray)) [also (set of ints): oSet = new LinkedHashSet<Integer>(Arrays.asList(oArray))] [requires (Arrays): import java.util.*] JavaScript: oSet = new Set(oArray) Kotlin: oSet = oArray.toMutableSet() [also: oSet = oArray.toSet()] PHP: ___ Python: oSet = set(oList) R: ___ Ruby: oSet = oArray.to_set [requires: require "set"] Rust: oSet = HashSet::from(oArray) [requires: use std::collections::HashSet] Scala: oSet = oArray.toSet SQL (MySQL): CREATE TABLE MyTableNew AS SELECT v FROM MyTable GROUP BY v ORDER BY min(k) SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT v FROM MyTable GROUP BY v ORDER BY min(k) SQL (SQLite): CREATE TABLE MyTableNew AS SELECT v FROM MyTable GROUP BY v ORDER BY min(k) Swift: oSet = Set(oArray) UFL: (Array.ToBuffer) [array of integers to binary data buffer] AutoHotkey: ___ [can use: Buffer() and NumPut()] C++: for (int i=0; i<vSize; i++) oBuf[i] = (unsigned char)oArray[i] [beforehand: unsigned char* oBuf = new unsigned char[vSize]] C#: byte[] oBuf = oArray.Select(v=>(byte)v).ToArray() Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) oBuf[i] = (byte)oArray[i] [beforehand: byte[] oBuf = new byte[oArray.length]] JavaScript: oBuf = Uint8Array.from(oArray) [also: oBuf = new Uint8Array(oArray.length)] Kotlin: oBuf = ByteArray(oArray.size){k->oArray[k]!!.toByte()} [note: the ByteArray constructor takes a size and an int-to-byte function: <init>(size: Int, init: (Int) -> Byte)] [also: oBuf = oArray.map{it.toByte()}.toByteArray()] PHP: ___ Python: oBuf = bytearray(oList) R: ___ Ruby: ___ Rust: oBuf: Vec<u8> = oVec.into_iter().map(|v| v as u8).collect() Scala: oBuf = oArray.map(_.toByte) [FIXME] SQL (MySQL): ___ [can use (string to hex): hex(MyCol)] [FIXME] SQL (PostgreSQL): ___ [can use (string to hex): hex(MyCol)] SQL (SQLite): ___ [can use (string to hex): hex(MyCol)] Swift: oBuf = [UInt8](repeating:0, count:oArray.count).enumerated().map{oArray[$0.0]} [note: failed with $0] UFL: Array.ToList [array to list] AutoHotkey: ___ C++: ___ [e.g. int array: std::list<int> oList(std::begin(oArray), std::end(oArray))] [e.g. string array: std::list<std::string> oList(std::begin(oArray), std::end(oArray))] [requires: #include <list>] C#: var oList = oArray.ToList() [requires (ToList): using System.Linq] Crystal: ___ Excel: ___ Excel VBA: ___ Go: oSlice := oArray[:] Java: ___ [e.g. int array: var oList = Arrays.stream(oArray).boxed().collect(Collectors.toList())] [e.g. string array: var oList = Arrays.asList(oArray)] [also: string array: var oList = Arrays.stream(oArray).collect(Collectors.toList())] [also: string array: var oList = new ArrayList<String>(Arrays.asList(oArray))] [WARNING: e.g. for String[]/Integer[] (but not int[]), if do 'oList = Arrays.asList(oArray)', modifying oList or oArray modifies both] [WARNING: e.g. for int[], if do 'oList = Arrays.asList(oArray)', oList contains 1 int[], not 0 or more ints] [requires (Collectors): import java.util.stream.*] [requires (Arrays/ArrayList): import java.util.*] JavaScript: ___ Kotlin: var oList = oArray.toList() [also: var oList = oArray.toMutableList()] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: oList = oArray.toList [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Array.FromList [or List.ToArray][list to array (array from list)] AutoHotkey: ___ C++: std::copy(oList.begin(), oList.end(), oArray) [beforehand (string array): auto* oArray = new std::string[oList.size()]] [beforehand (int array): auto* oArray = new int[oList.size()]] [requires (copy): #include <algorithm>] C#: var oArray = oList.ToArray() Crystal: ___ Excel: ___ Excel VBA: ___ Go: copy(oArray[:], oSlice) [note: if the array is smaller, values are omitted, if the array is larger, default values fill the gaps (e.g. 0/"")] Java: ___ [e.g. int[] oArray = oList.stream().mapToInt(v->v).toArray()] [e.g. String[] oArray = oList.toArray(new String[0])] [note: 'String[0]' is an optimisation (alternatively: 'String[oArray.length]')] JavaScript: ___ Kotlin: oArray = oList.toTypedArray() PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: oArray = oList.toArray [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Array.ToVector [array to vector] AutoHotkey: ___ C++: ___ [e.g. int array: std::vector<int> oVec(std::begin(oArray), std::end(oArray))] [e.g. string array: std::vector<std::string> oVec(std::begin(oArray), std::end(oArray))] [requires: #include <vector>] C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: oVec = oArray.to_vec() Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Array.FromVector [or Vector.ToArray][vector to array (array from vector)] AutoHotkey: ___ C++: std::copy(oVec.begin(), oVec.end(), oArray) [also: for (int i=0; i<oVec.size(); i++) oArray[i] = oVec[i]] [beforehand (string array): auto* oArray = new std::string[oVec.size()]] [beforehand (int array): auto* oArray = new int[oVec.size()]] [requires (copy): #include <algorithm>] C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: oArray = oVec.try_into().expect("my error message") [WARNING: array and vector must have the same length] Scala: ___ [FIXME] SQL (MySQL): ___ [FIXME] SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.IntToStrArray) [int array to string array] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oArrayNew[i] = std::to_string(oArray[i]) [e.g. int array to std::string array] [also: std::vector<std::string> oVecNew; for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oVecNew.push_back(std::to_string(oArray[i]));] C#: oArrayNew = oArray.Select(v=>v.ToString()).ToArray() Crystal: oArrayNew = oArray.map(&.to_s) Excel: ___ Excel VBA: ___ Go: ___ [can use: oSliceNew := strings.Fields(strings.Trim(fmt.Sprint(oArray), "[]"))] Java: for (int i=0; i<oArray.length; i++) oArrayNew[i] = "" + oArray[i] [beforehand: var oArrayNew = new String[oArray.length]] [also: String[] oArrayNew = Arrays.stream(oArray).mapToObj(String::valueOf).toArray(String[]::new)] [also: String[] oArrayNew = Arrays.stream(oArray).mapToObj(Integer::toString).toArray(String[]::new)] [also: var oListNew = oList.stream().map(Object::toString).collect(Collectors.toList())] [requires (Collectors): import java.util.stream.*] JavaScript: oArrayNew = oArray.map(String) [also: oArrayNew = oArray.map(v=>String(v))] Kotlin: oArrayNew = oArray.map{it.toString()}.toTypedArray() [also: oArrayNew = oArray.map{v->v.toString()}.toTypedArray()] PHP: $oArrayNew = array_map("strval", $oArray) [also: $oArrayNew = array_map(fn($v)=>strval($v), $oArray)] Python: oListNew = list(map(str, oList)) [also: oListNew = list(map(lambda v:str(v), oList))] R: oVecNew = as.character(oVec) Ruby: oArrayNew = oArray.map(&:to_s) Rust: oVecNew = oArray.iter().map(|v| (*v).to_string()).collect::<Vec<_>>() [note: also works with vectors] Scala: oArrayNew = oArray.map(_.toString) [note: also works with lists] SQL (MySQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS CHAR) AS v FROM MyTable [WARNING: a column can be defined as 'TEXT', but values can't be cast to 'TEXT', e.g. use 'CHAR' instead] SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS TEXT) AS v FROM MyTable [also: MyArray::text[]] SQL (SQLite): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS TEXT) AS v FROM MyTable Swift: oArrayNew = oArray.map(String.init) [also: oArrayNew = oArray.map{String($0)}] UFL: (Array.StrToIntArray) [string array to int array] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oArrayNew[i] = std::stoi(oArray[i]) [e.g. std::string array to int array] [also: std::vector<int> oVecNew; for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oVecNew.push_back(std::stoi(oArray[i]));] C#: oArrayNew = oArray.Select(v=>Int32.Parse(v)).ToArray() Crystal: oArrayNew = oArray.map(&.to_i) Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) oArrayNew[i] = Integer.parseInt(oArray[i]) [beforehand: var oArrayNew = new String[oArray.length]] [also: int[] oArrayNew = Stream.of(oArray).mapToInt(Integer::parseInt).toArray()] [also: int[] oArrayNew = Arrays.stream(oArray).mapToInt(Integer::parseInt).toArray()] [also: var oListNew = oList.stream().mapToInt(Integer::parseInt).boxed().collect(Collectors.toList())] [requires (Collectors): import java.util.stream.*] JavaScript: oArrayNew = oArray.map(v=>parseInt(v)) [WARNING: doesn't work because the key index is passed as the radix: oArray.map(parseInt)] Kotlin: oArrayNew = oArray.map{it.toInt()}.toTypedArray() [also: oArrayNew = oArray.map{v->v.toInt()}.toTypedArray()] PHP: $oArrayNew = array_map("intval", $oArray) [also: $oArrayNew = array_map(fn($v)=>intval($v), $oArray)] Python: oListNew = list(map(int, oList)) [also: oListNew = list(map(lambda v:int(v), oList))] R: oVecNew = as.integer(oVec) [also: oVecNew = as.numeric(as.integer(oVec))] Ruby: oArrayNew = oArray.map(&:to_i) Rust: oVecNew = oArray.iter().map(|v| v.parse::<i32>().unwrap()).collect::<Vec<_>>() [note: also works with vectors] Scala: oArrayNew = oArray.map(_.toInt) [note: also works with lists] SQL (MySQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS SIGNED) AS v FROM MyTable SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS INTEGER) AS v FROM MyTable [also: MyArray::int[]] SQL (SQLite): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS INTEGER) AS v FROM MyTable Swift: oArrayNew = oArray.compactMap(Int.init) [also: oArrayNew = oArray.compactMap{Int($0)}] UFL: (Array.IntToFloatArray) [int array to float array] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oArrayNew[i] = (double)oArray[i] C#: oArrayNew = oArray.Select(v=>(double)v).ToArray() Crystal: oArrayNew = oArray.map(&.to_f) Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) oArrayNew[i] = (double)oArray[i] [beforehand: var oArrayNew = new double[oArray.length]] [also: double[] oArrayNew = IntStream.of(oArray).mapToDouble(v->(double)v).toArray()] [also: double[] oArrayNew = Arrays.stream(oArray).mapToDouble(v->(double)v).toArray()] [also: var oListNew = oList.stream().mapToDouble(v->v).boxed().collect(Collectors.toList())] [also: double[] oArrayNew = Arrays.stream(oArray).asDoubleStream().toArray()] [requires (Collectors): import java.util.stream.*] JavaScript: oArrayNew = oArray [the Number type handles ints and floats] Kotlin: oArrayNew = oArray.map{it.toDouble()}.toTypedArray() [also: oArrayNew = oArray.map{v->v.toDouble()}.toTypedArray()] PHP: $oArrayNew = array_map("floatval", $oArray) [also: $oArrayNew = array_map(fn($v)=>floatval($v), $oArray)] Python: oListNew = list(map(float, oList)) [also: oListNew = list(map(lambda v:float(v), oList))] R: oVecNew = as.numeric(oVec) Ruby: oArrayNew = oArray.map(&:to_f) Rust: oVecNew = oArray.iter().map(|v| *v as f64).collect::<Vec<_>>() [note: also works with vectors] Scala: oArrayNew = oArray.map(_.toDouble) [note: also works with lists] SQL (MySQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS DOUBLE) AS v FROM MyTable SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS FLOAT) AS v FROM MyTable [also: MyArray::float[]] SQL (SQLite): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS REAL) AS v FROM MyTable Swift: oArrayNew = oArray.map{Double($0)} UFL: (Array.FloatToIntArray) [float array to int array] AutoHotkey: ___ C++: for (int i=0; i<sizeof(oArray)/sizeof(oArray[0]); i++) oArrayNew[i] = (int)oArray[i] C#: oArrayNew = oArray.Select(v=>(int)v).ToArray() Crystal: oArrayNew = oArray.map(&.to_i) Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) oArrayNew[i] = (int)oArray[i] [beforehand: var oArrayNew = new int[oArray.length]] [also: int[] oArrayNew = DoubleStream.of(oArray).mapToInt(v->(int)v).toArray()] [also: int[] oArrayNew = Arrays.stream(oArray).mapToInt(v->(int)v).toArray()] [also: var oListNew = oList.stream().mapToInt(v->v.intValue()).boxed().collect(Collectors.toList())] [requires (Collectors): import java.util.stream.*] JavaScript: oArrayNew = oArray.map(v=>Math.trunc(v)) [also: oArrayNew = oArray.map(v=>parseInt(v.toFixed()))] [WARNING: doesn't work because the key index is passed as the radix: oArray.map(parseInt)] Kotlin: oArrayNew = oArray.map{it.toInt()}.toTypedArray() [also: oArrayNew = oArray.map{v->v.toInt()}.toTypedArray()] PHP: $oArrayNew = array_map("intval", $oArray) [also: $oArrayNew = array_map(fn($v)=>intval($v), $oArray)] Python: oListNew = list(map(int, oList)) [also: oListNew = list(map(lambda v:int(v), oList))] R: oVecNew = as.integer(oVec) [also: oVecNew = as.numeric(as.integer(oVec))] Ruby: oArrayNew = oArray.map(&:to_i) Rust: oVecNew = oArray.iter().map(|v| *v as i32).collect::<Vec<_>>() [also: oVecNew = oArray.iter().map(|&v| v as i32).collect::<Vec<_>>()] [note: also works with vectors] Scala: oArrayNew = oArray.map(_.toInt) [note: also works with lists] SQL (MySQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS SIGNED) AS v FROM MyTable SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS INTEGER) AS v FROM MyTable [also: MyArray::int[]] [also: MyArray::numeric[]::int[]] [MAJOR WARNING: MyFloat::int can give unpredictable results] SQL (SQLite): CREATE TABLE MyTableNew AS SELECT k,CAST(v AS INTEGER) AS v FROM MyTable Swift: oArrayNew = oArray.map{Int($0)} UFL: Array.ToVars [array to variables, e.g. a, b, c = myarray][note: often done by destructuring assignment][see also: VarDeclSetMult] AutoHotkey: ___ C++: ___ C#: ___ [can use (list patterns): if (oArray is [var vVar1, var vVar2, var vVar3])] [also: var (vVar1, vVar2, vVar3) = (oArray[0], oArray[1], oArray[2])] Crystal: vVar1, vVar2, vVar3 = oArray Excel: ___ Excel VBA: ___ Go: ___ [can use: vVar1, vVar2, vVar3 := oSlice[0], oSlice[1], oSlice[2]] Java: ___ JavaScript: [vVar1, vVar2, vVar3] = oArray Kotlin: var (vVar1, vVar2, vVar3) = oArray [note: can do destructuring declaration, but not destructuring assignment] PHP: [$vVar1, $vVar2, $vVar3] = $oArray Python: vVar1, vVar2, vVar3 = oList [WARNING: throws if list has too many values, workaround: vVar1, vVar2, vVar3, *_ = oList] R: ___ Ruby: vVar1, vVar2, vVar3 = oArray Rust: let [mut vVar1, mut vVar2, mut vVar3] = oArray [WARNING: throws if array has too many values, workaround: let [mut vVar1, mut vVar2, mut vVar3, oDummy @ ..] = oArray] Scala: var Array(vVar1, vVar2, vVar3) = oArray [WARNING: throws if array has too many values, workaround: var Array(vVar1, vVar2, vVar3, _*) = oArray] [note: can do destructuring declaration, but not destructuring assignment] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: var (vVar1, vVar2, vVar3) = (oArray[0], oArray[1], oArray[2])] UFL: (Array.CodepointsToShorts) [or Array.SplitCodepoints][array of 1-char strings, split any surrogate pairs][e.g. ["a","𝄞"] to ["a",Str(Chr(55348)),Str(Chr(56606))]][see also: StrSplitChars/Array.FlatMap/StrSurrogatePairDemo] AutoHotkey: ___ C++: ___ C#: oArrayNew = oArray.SelectMany(v=>Regex.Split(v, "(?<=\\G.)(?!$)")).ToArray() Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: String[] oArrayNew = Arrays.stream(oArray).map(v->v.split("")).flatMap(Stream::of).toArray(String[]::new) JavaScript: oArrayNew = oArray.flatMap(v=>v.split("")) Kotlin: oArrayNew = oArray.flatMap{it.chunked(1)}.toTypedArray() PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: oArrayNew = oArray.flatMap(_.split("")) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Array.ShortsToCodepoints) [or Array.JoinCodepoints][array of 1-char strings, join any surrogate pairs][e.g. ["a",Str(Chr(55348)),Str(Chr(56606))] to ["a","𝄞"]][see also: Array.GroupByWithIndex/Ord/Between/Map.Values/Array.Concat] AutoHotkey: ___ C++: ___ C#: oArrayNew = oArray.Select((v,k)=>new{k=k,v=v}).GroupBy(e=>e.k - (Math.Clamp((int)e.v[0], 0xDC00, 0xDFFF) == e.v[0] ? 1 : 0)).ToDictionary(g=>g.Key, g=>String.Concat(g.Select(e=>e.v).ToArray())).Values.ToArray() [requires (GroupBy/Select/ToDictionary): using System.Linq] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: String[] oArrayNew = IntStream.range(0, oArray.length).boxed().collect(Collectors.groupingBy(k->k - (0xDC00 <= oArray[k].codePointAt(0) && oArray[k].codePointAt(0) <= 0xDFFF ? 1 : 0), Collectors.mapping(i->oArray[i], Collectors.toList()))).values().stream().map(v->String.join("", v)).toArray(String[]::new) JavaScript: oArrayNew = [...Map.groupBy(oArray, (v,k)=>k - (0xDC00 <= v.codePointAt() && v.codePointAt() <= 0xDFFF)).values()].map(v=>v.join("")) Kotlin: oArrayNew = oArray.withIndex().groupBy({it.index - (if ((0xDC00..0xDFFF).contains(it.value.codePointAt(0))) 1 else 0)}, {it.value}).values.map{it.joinToString("")}.toTypedArray() PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ [can use: var oMapTemp = scala.collection.mutable.LinkedHashMap[Int,List[String]]().withDefaultValue(List[String]()); oArray.view.zipWithIndex.foreach((v,k)=>oMapTemp(k - (if (0xDC00 <= v.codePointAt(0) && v.codePointAt(0) <= 0xDFFF) 1 else 0)):+=v); var oArrayNew = oMapTemp.values.map(_.mkString("")).toArray] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___
UFL: Map.Print [or Map.PrintKeyValue][print the key-value pairs][see also: PrintKeyValueAsPair/Map.ToString] AutoHotkey: ___ C++: for (const auto& [k, v] : oMap) std::cout << k << ":" << v << "\n" C#: Console.WriteLine(String.Join("\n", oDict)) [also: Console.WriteLine(String.Join("\n", oDict.Select(e=>$"{e.Key}:{e.Value}")))] [requires (Select): using System.Linq] Crystal: p oMap Excel: ___ Excel VBA: ___ Go: fmt.Println(oMap) [requires: import "fmt"] Java: System.out.println(oMap) JavaScript: console.log(oMap) [also: console.log([...oMap.entries()].join("\n"))] Kotlin: println(oMap) PHP: var_export($oMap) [also: var_dump($oMap)] [also: print_r($oMap)] [also (array-like printed as array, map-like printed as object): echo json_encode($oMap) . "\n"] Python: print(oDict) R: for (k in names(oMap)) {print(paste(k, oMap[k], sep=": "))} [also: print(paste(names(oMap), oMap, sep = ": ", collapse = ", "))] Ruby: p oMap Rust: println!("{:?}", oMap) [also: println!("{:#?}", oMap)] [also (print using alphabetical/numerical order, via a BTreeMap): println!("{:?}", oMap.iter().collect::<BTreeMap<_,_>>())] [requires (BTreeMap): use std::collections::BTreeMap] Scala: println(oMap) SQL (MySQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] SQL (PostgreSQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] SQL (SQLite): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] Swift: print(oDict) [also (print using alphabetical/numerical order): print(oDict.map{($0,$1)}.sorted(by:{$0.0<$1.0}))] UFL: Map.LoopKeyValue [loop through the items of a map/dictionary, get key-value pairs one-by-one] AutoHotkey: for k,v in oMap C++: for (const auto& [k,v] : oMap) C#: foreach (var oEntry in oDict) [also: foreach (KeyValuePair<string,string> oEntry in oDict)] [note: oEntry.Key, oEntry.Value] [requires (KeyValuePair): using System.Collections.Generic] Crystal: oMap.each do |k,v| [afterwards: end] Excel: ___ Excel VBA: For Each v In oColl [afterwards: Next] [WARNING: for a Collection object, can loop through values, but not keys, must store a list of keys manually] Go: for k, v := range oMap Java: for (var oEntry : oMap.entrySet()) [note: oEntry.getKey(), oEntry.getValue()] JavaScript: for (const [k,v] of oMap) [also (ES6): oMap.forEach(function (v, k) {...})] Kotlin: for ((k,v) in oMap) PHP: foreach ($oMap as $k=>$v) Python: for k,v in oDict.items(): R: for (k in names(oMap)) [note: v = oMap[[k]]] [also: v = unname(oMap[k])] [note: double square brackets] Ruby: for k,v in oMap [afterwards: end] Rust: for (k,v) in &oMap [also: for oPair in &oMap] [note: can omit '&', if don't intend to iterate through map again] Scala: for ((k,v) <- oMap) [also (tuple): for (oEntry <- oMap)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for (k,v) in oDict UFL: Map.ForEach [or Map.LoopForEach][call a function once for each item of a map][see also: Map.LoopKeyValue] AutoHotkey: ___ C++: ___ [can use: for (const auto& [k,v] : oMap) oFunc(k, v)] C#: ___ [can use: foreach (var e in oDict) oFunc(e.Key,e.Value)] [note: e for entry] Crystal: oMap.each{|k,v| oFunc.call(k,v)} Excel: ___ Excel VBA: ___ Go: ___ Java: oMap.forEach(oFunc) [also: oMap.forEach((k,v)->oFunc.accept(k,v))] [note: Func receives key/value] JavaScript: oMap.forEach(oFunc) [also: oMap.forEach((v,k)=>oFunc(k,v))] [note: Func receives value/key/object] Kotlin: oMap.forEach(oFunc) [also: oMap.forEach{(k,v)->oFunc(k,v)}] [note: Func receives key/value] PHP: array_walk($oMap, $oFunc) [also: array_walk($oMap, fn($v,$k)=>$oFunc($k,$v))] [also: foreach ($oMap as $k=>$v) $oFunc($k,$v)] Python: ___ [can use: for k,v in oDict.items(): oFunc(k,v)] R: for (k in names(oMap)) {oFunc(k, oMap[k])} Ruby: oMap.each_pair{|k,v| oFunc.call(k,v)} Rust: oMap.iter().for_each(|(k,v)| oFunc(k,v)) Scala: oMap.foreach(oFunc) [also: oMap.foreach(e=>oFunc(e))] [also: oMap.foreach((k,v)=>oFunc(k,v))] [note: Func receives key/value] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oDict.forEach(oFunc) [also: oDict.forEach{oFunc($0,$1)}] [note: Func receives key/value] UFL: Map.NewEmpty [or Map.NewBasic/Map.EmptyNew][create an empty map][see also: Map.OrderType] AutoHotkey: oMap := Map() [type: Map] [note: key order alphabetical (case-sensitive)] [note: AHK v1: key order alphabetical (case *insensitive*)] C++: std::map<std::string,std::string> oMap [requires: #include <map>] [note: key order alphabetical (case-sensitive)] [type: std::map<std::string, std::string> (typeid: NSt3__23mapINS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEES6_NS_4lessIS6_EENS4_INS_4pairIKS6_S6_EEEEEE)] [e.g. other map types: std::map<int,int>, std::map<double,double>] [note: type: the space after the comma can be omitted] C#: var oDict = new Dictionary<string,string> {} [requires (Dictionary): using System.Collections.Generic] [type: Dictionary`2 (e.g. <int,int>/<double,double>/<string,string> dictionaries)] Crystal: oMap = {} of String => String [type: e.g. Hash(String, String)] Excel: ___ Excel VBA: Set oColl = New Collection [also: Dim oColl As New Collection] [type: Collection] [note: 1-based] [note: an alternative class: Set oDict = CreateObject("Scripting.Dictionary")] [WARNING: Excel Collection keys can't be retrieved via a loop, so store them in a separate array/collection] Go: oMap := make(map[string]string) [type: e.g. map[string]string] Java: LinkedHashMap<String,String> oMap = new LinkedHashMap<>() [requires (LinkedHashMap): import java.util.*] [type: LinkedHashMap] JavaScript: oMap = new Map() [type: Map] Kotlin: oMap = mutableMapOf<String, String>() [also: mapOf()] [type (mutableMapOf): LinkedHashMap] [type (mapOf): SingletonMap] PHP: $oMap = [] [type: array] [also: array()] [note: an associative array that also has linear array functions] Python: oDict = {} [type: dict] [WARNING: creates a dictionary, not an object] R: oMap = character(0) [e.g. type: character] [e.g. oMap = numeric(0)] [e.g. type: double (class: numeric)] [also (1-item map to 0-item map): oMap = c(0)[-1]] [note: 1-based] [WARNING: for vectors, typeof/class report the type of the item] [i.e. for a 'map', we use a vector with named values] Ruby: oMap = {} [type: Hash] Rust: let mut oMap: HashMap<&str,&str> = HashMap::new() [type: e.g. std::collections::hash::map::HashMap<&str, &str>] [requires: use std::collections::HashMap] Scala: oMap = scala.collection.mutable.LinkedHashMap[String,String]() [type: LinkedHashMap] [also: var oMap = scala.collection.mutable.Map[String,String]()] [type (Map): HashMap] SQL (MySQL): CREATE TABLE MyTable (k TEXT, v TEXT) [type: (table)] SQL (PostgreSQL): CREATE TABLE MyTable (k TEXT, v TEXT) [type: (table)] SQL (SQLite): CREATE TABLE MyTable (k ANY, v ANY) STRICT [type: (table)] Swift: oDict = [String: String]() [type: e.g. Dictionary<String,String>] [WARNING: 'random' key order, not insertion order] [can use (insertion order, but allows duplicates) e.g. oDict: KeyValuePairs = ["k1":"v1", "k2":"v2", "k3":"v3"]] UFL: (Map.NewStrDemo) [or Map.NewStrStrDemo][initialise a map/dictionary with 3 items][see also: Map.FromEntries] AutoHotkey: oMap := Map("k1","v1", "k2","v2", "k3","v3") C++: std::map<std::string,std::string> oMap = {{"k1","v1"},{"k2","v2"},{"k3","v3"}} C#: var oDict = new Dictionary<string,string> {{"k1","v1"},{"k2","v2"},{"k3","v3"}} [requires (Dictionary): using System.Collections.Generic] Crystal: oMap = {"k1"=>"v1","k2"=>"v2","k3"=>"v3"} Excel: ___ Excel VBA: ___ [e.g. Set oColl = New Collection] [e.g. Call oColl.Add("v1", "k1")] Go: oMap := map[string]string{"k1": "v1", "k2": "v2", "k3": "v3"} Java: LinkedHashMap<String,String> oMap = Arrays.stream(oEntries).collect(LinkedHashMap::new, (a,e)->a.put(e[0],e[1]), Map::putAll) [also: for (String[] e : oEntries) oMap.put(e[0], e[1])] [also (random order, not insertion order): HashMap<String,String> oMap = new HashMap<>(Map.of("k1","v1", "k2","v2", "k3","v3"))] [e.g. String[][] oEntries = {{"k1","v1"},{"k2","v2"},{"k3","v3"}}] [requires (Arrays): import java.util.*] [e.g. empty string/string map: LinkedHashMap<String,String> oMap = new LinkedHashMap<>()] JavaScript: oMap = new Map([["k1","v1"], ["k2","v2"], ["k3","v3"]]) [also: oMap = new Map(); [["k1","v1"], ["k2","v2"], ["k3","v3"]].forEach(function (v) {oMap.set(v[0], v[1])});] Kotlin: oMap = mutableMapOf("k1" to "v1", "k2" to "v2", "k3" to "v3") [also: mapOf()] PHP: $oMap = ["k1"=>"v1", "k2"=>"v2", "k3"=>"v3"] Python: oDict = {"k1":"v1", "k2":"v2", "k3":"v3"} [WARNING: creates a dictionary, not an object] R: oMap = c("k1"="v1", "k2"="v2", "k3"="v3") [note: workaround: using names as 'keys'] [WARNING: names can be used multiple times, they don't have to be unique] Ruby: oMap = {"k1"=>"v1","k2"=>"v2","k3"=>"v3"} Rust: let mut oMap = HashMap::from([("k1","v1"), ("k2","v2"), ("k3","v3")]) [requires: use std::collections::HashMap] Scala: oMap = scala.collection.mutable.LinkedHashMap("k1"->"v1", "k2"->"v2", "k3"->"v3") [also: var oMap = Map("k1"->"v1", "k2"->"v2", "k3"->"v3")] SQL (MySQL): CREATE TABLE MyTable (k TEXT, v TEXT); INSERT INTO MyTable VALUES ('k1','v1'), ('k2','v2'), ('k3','v3'); SQL (PostgreSQL): CREATE TABLE MyTable (k TEXT, v TEXT); INSERT INTO MyTable VALUES ('k1','v1'), ('k2','v2'), ('k3','v3'); [note: 'hstore' objects can store string key-string value pairs] SQL (SQLite): CREATE TABLE MyTable (k TEXT, v TEXT) STRICT; INSERT INTO MyTable VALUES ('k1','v1'), ('k2','v2'), ('k3','v3'); Swift: oDict = ["k1":"v1", "k2":"v2", "k3":"v3"] UFL: (Map.NewStrIntDemo) [initialise a map/dictionary with 3 items][see also: Tuple.NewDemo] AutoHotkey: oMap := Map("k1",1, "k2",2, "k3",3) C++: std::map<std::string,int> oMap = {std::make_pair("k1",1),std::make_pair("k2",2),std::make_pair("k3",3)} [requires (make_pair): #include <utility>] C#: var oDict = new[]{("k1",1),("k2",2),("k3",3)}.ToDictionary() [requires (ToDictionary): using System.Linq] Crystal: oMap = {"k1"=>1,"k2"=>2,"k3"=>3} Excel: ___ Excel VBA: ___ [e.g. Set oColl = New Collection] [e.g. Call oColl.Add(1, "k1")] Go: oMap := map[string]int{"k1": 1, "k2": 2, "k3": 3} Java: LinkedHashMap<String,Integer> oMap = Arrays.stream(oEntries).collect(LinkedHashMap::new, (a,e)->a.put(e[0],Integer.parseInt(e[1])), Map::putAll) [also: for (String[] e : oEntries) oMap.put(e[0], Integer.parseInt(e[1]))] [also (random order, not insertion order): HashMap<String,Integer> oMap = new HashMap<>(Map.of("k1",1, "k2",2, "k3",3))] [e.g. (store ints as strings, to later convert them to ints) String[][] oEntries = {{"k1","1"},{"k2","2"},{"k3","3"}}] [requires (Arrays): import java.util.*] [e.g. empty string/int map: LinkedHashMap<String,Integer> oMap = new LinkedHashMap<>()] JavaScript: oMap = new Map([["k1",1], ["k2",2], ["k3",3]]) [also: oMap = new Map(); [["k1",1], ["k2",2], ["k3",3]].forEach(function (v) {oMap.set(v[0], v[1])});] Kotlin: oMap = mutableMapOf("k1" to 1, "k2" to 2, "k3" to 3) [also: mapOf()] PHP: $oMap = ["k1"=>1, "k2"=>2, "k3"=>3] Python: oDict = {"k1":1, "k2":2, "k3":3} [WARNING: creates a dictionary, not an object] R: oMap = c("k1"=1, "k2"=2, "k3"=3) Ruby: oMap = {"k1"=>1,"k2"=>2,"k3"=>3} Rust: let mut oMap = HashMap::from([("k1",1), ("k2",2), ("k3",3)]) [requires: use std::collections::HashMap] Scala: oMap = scala.collection.mutable.LinkedHashMap("k1"->1, "k2"->2, "k3"->3) [also: var oMap = Map("k1"->1, "k2"->2, "k3"->3)] SQL (MySQL): CREATE TABLE MyTable (k TEXT, v INTEGER); INSERT INTO MyTable VALUES ('k1',1), ('k2',2), ('k3',3); SQL (PostgreSQL): CREATE TABLE MyTable (k TEXT, v INTEGER); INSERT INTO MyTable VALUES ('k1',1), ('k2',2), ('k3',3); SQL (SQLite): CREATE TABLE MyTable (k TEXT, v INTEGER) STRICT; INSERT INTO MyTable VALUES ('k1',1), ('k2',2), ('k3',3); Swift: oDict = ["k1":1, "k2":2, "k3":3] UFL: (Map.OrderType) [insertion order, alphabetical order, 'random' order (unordered)][e.g. what order does a loop return] AutoHotkey: ___ [item order: Map: alphabetical (case-sensitive)/numerical] [note: AHK v1: item order: alphabetical (case-*insensitive*)/numerical] [can use (insertion order map): Scripting.Dictionary] C++: ___ [item order: map: alphabetical (case-sensitive)/numerical] [also: item order: unordered_map: 'random'] C#: ___ [item order: Dictionary: insertion] Crystal: ___ [item order: Hash: insertion] Excel: ___ Excel VBA: ___ Go: ___ [item order: map: insertion] Java: ___ [item order: LinkedHashMap: insertion (or optionally access)] [WARNING: item order: HashMap: 'random'] JavaScript: ___ [item order: Map: insertion] Kotlin: ___ [item order: LinkedHashMap (mutableMapOf): insertion] PHP: ___ [item order: array: insertion] Python: ___ [item order: dict: insertion] R: ___ [item order: character/double (vector): insertion] Ruby: ___ [item order: Hash: insertion] Rust: ___ [item order: BTreeMap: alphabetical (case-sensitive)/numerical] [item order: HashMap: 'random'] Scala: ___ [item order: LinkedHashMap: insertion] SQL (MySQL): ___ [item order: (table): insertion] SQL (PostgreSQL): ___ [item order: (table): insertion] SQL (SQLite): ___ [item order: (table): insertion] Swift: ___ [WARNING: item order: Dictionary: 'random'] UFL: Map.Keys [get keys as an array] AutoHotkey: oKeys := [oMap*] [algorithm: variadic function calls: 'If the object is not an Array, __Enum is called with a count of 1 and the enumerator is called with only one parameter at a time.'] C++: for (const auto& [vKey, _] : oMap) oKeys.push_back(vKey) [beforehand: std::vector<std::string> oKeys] [beforehand (also): oKeys.reserve(oMap.size())] C#: var oKeys = oDict.Keys.ToArray() Crystal: oKeys = oMap.keys Excel: ___ Excel VBA: ___ Go: ___ Java: String[] oKeys = oMap.keySet().toArray(new String[oMap.size()]) JavaScript: oKeys = [...oMap.keys()] [also (returns an iterator): oKeys = oMap.keys()] Kotlin: oKeys = oMap.keys PHP: $oKeys = array_keys($oMap) Python: oKeys = list(oDict) [also: oDict.keys()] R: oKeys = names(oMap) Ruby: oKeys = oMap.keys Rust: oKeys = oMap.keys() Scala: oKeys = oMap.keys().toArray SQL (MySQL): SELECT k FROM MyTable SQL (PostgreSQL): SELECT k FROM MyTable SQL (SQLite): SELECT k FROM MyTable Swift: oKeys = oDict.keys UFL: Map.Values [get values as an array] AutoHotkey: oValues := [oMap.__Enum(2).Bind(&_)*] [algorithm: 'Bind(&_)' fills param 1 and leaves param 2 unchanged, before: 2 params, k/v, after: 1 param, v] C++: for (const auto& [_, vValue] : oMap) oValues.push_back(vValue) [beforehand: std::vector<std::string> oValues] [beforehand (also): oValues.reserve(oMap.size())] C#: var oValues = oDict.Values.ToArray() Crystal: oValues = oMap.values Excel: ___ Excel VBA: ___ Go: ___ Java: String[] oValues = oMap.values().toArray(new String[oMap.size()]) JavaScript: oValues = [...oMap.values()] [also (returns an iterator): oValues = oMap.values()] Kotlin: oValues = oMap.values PHP: $oValues = array_values($oMap) Python: oValues = oDict.values() R: oValues = unname(oMap) Ruby: oValues = oMap.values Rust: oValues = oMap.values() Scala: oValues = oMap.values().toArray SQL (MySQL): SELECT v FROM MyTable SQL (PostgreSQL): SELECT v FROM MyTable SQL (SQLite): SELECT v FROM MyTable Swift: oValues = oDict.values UFL: Map.Entries [or Map.ToEntries][map to entries (key-value pairs)] AutoHotkey: ___ C++: for (const auto& [vKey, vValue] : oMap) oEntries.push_back({vKey, vValue}) [beforehand: std::vector<std::vector<std::string>> oEntries] [beforehand (also): oEntries.reserve(oMap.size())] [note: returns a vector of vectors] [also (to handle values of different types): std::pair] C#: string[][] oEntries = oDict.Select(e=>new[]{e.Key,e.Value}).ToArray() [note: returns an array of arrays] Crystal: oEntries = oMap.to_a [note: returns an array of tuples] Excel: ___ Excel VBA: ___ Go: ___ Java: String[][] oEntries = oMap.entrySet().stream().map(e->new String[]{e.getKey(),e.getValue()}).toArray(String[][]::new) [note: returns an array of tuples] JavaScript: oEntries = [...oMap.entries()] [note: returns an array of arrays] [also (returns an iterator): oEntries = oMap.entries()] Kotlin: oEntries = oMap.entries.toTypedArray() [note: returns an array of entries] [also (returns an iterator): oEntries = oMap.entries] [also (returns an array of pairs): oEntries = oMap.toList().toTypedArray()] PHP: foreach ($oMap as $vKey=>$vValue) array_push($oEntries, [$vKey, $vValue]) [beforehand: $oEntries = []] [also: $oEntries = array_map(function($oKey) use ($oMap) {return [$oKey, $oMap[$oKey]];}, array_keys($oMap))] [note: returns an array of arrays] Python: oEntries = list(oDict.items()) [note: returns a list of tuples] [also (returns an iterator): oEntries = oDict.items()] R: oEntries = Map(c, names(oMap), oMap, USE.NAMES=FALSE) [note: returns a list] Ruby: oEntries = oMap.to_a [note: returns an array of arrays] Rust: oEntries: Vec<(&&str,&&str)> = oMap.iter().collect() [note: returns a vector of tuples] Scala: oEntries = oMap.toArray [note: returns an array of tuples] SQL (MySQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] SQL (PostgreSQL): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] SQL (SQLite): SELECT * FROM MyTable [also: SELECT k,v FROM MyTable] Swift: oEntries = oDict.keys.map{[$0,oDict[$0]!]} [note: returns an array of arrays] [also (to tuples): oEntries = oDict.map{($0,$1)}] UFL: Map.Count [get key count][see also: Array.CountNonNull] AutoHotkey: vCount := oMap.Count C++: vCount = oMap.size() C#: vCount = oDict.Count Crystal: vCount = oMap.size Excel: ___ Excel VBA: vCount = oColl.Count Go: vCount = len(oMap) Java: vCount = oMap.size() JavaScript: vCount = oMap.size Kotlin: vCount = oMap.size [also: oMap.count()] PHP: $vCount = count($oMap) [also: sizeof($oMap)] Python: vCount = len(oDict) R: vCount = length(oMap) [also (exclude NAs): vCount = length(na.omit(oVec))] Ruby: vCount = oMap.size Rust: vCount = oMap.len() Scala: vCount = oMap.size SQL (MySQL): SELECT COUNT(*) FROM MyTable SQL (PostgreSQL): SELECT COUNT(*) FROM MyTable SQL (SQLite): SELECT COUNT(*) FROM MyTable Swift: vCount = oDict.count UFL: Map.Has [or Map.HasKey][does map have key with key name] AutoHotkey: vHasKey := oMap.Has(vKey) [deprecated (AHK v1): oMap.HasKey(vKey)] C++: vHasKey = oMap.count(vKey) [note: the 1-param version (overload) acts as a has-key method, returning 1 or 0] C#: vHasKey = oDict.ContainsKey(vKey) Crystal: vHasKey = oMap.has_key?(vKey) [also: oMap.includes?({vKey, vValue})] [WARNING: includes?() checks for a key-value pair, not a key] Excel: ___ Excel VBA: ___ [can use: 'Call oColl.Item(vKey)' with 'On Error GoTo', i.e. if it throws, the key doesn't exist] Go: vValue, vHasKey := oMap[vKey] Java: vHasKey = oMap.containsKey(vKey) JavaScript: vHasKey = oMap.has(vKey) Kotlin: vHasKey = oMap.contains(vKey) PHP: $vHasKey = array_key_exists($vKey, $oMap) Python: vHasKey = vKey in oDict [inverse: vKey not in oDict] [note: word order: 'not in' versus 'is not'] R: vHasKey = vKey %in% names(oMap) Ruby: vHasKey = oMap.include?(vKey) [alias (include?): has_key?/member?/key?] Rust: vHasKey = oMap.contains_key(vKey) Scala: vHasKey = oMap.contains(vKey) SQL (MySQL): SELECT 0 != COUNT(*) FROM MyTable WHERE k=MyKey SQL (PostgreSQL): SELECT 0 != COUNT(*) FROM MyTable WHERE k=MyKey SQL (SQLite): SELECT 0 != COUNT(*) FROM MyTable WHERE k==MyKey Swift: vHasKey = oDict.keys.contains(vKey) [also: vHasKey = (oDict[vKey] != nil)] UFL: (Map.GetDemo) [map get key value (fixed key name)] AutoHotkey: vValue := oMap["MyKey"] C++: vValue = oMap.at("MyKey") [also: vValue = oMap["MyKey"]] C#: vValue = oDict["MyKey"] Crystal: vValue = oMap["MyKey"] Excel: ___ Excel VBA: vValue = oColl.Item("MyKey") Go: vValue := oMap["MyKey"] [also: vValue, vHasKey := oMap["MyKey"]] [WARNING: non-existent key: returns default value (e.g. 0/"")] Java: vValue = oMap.get("MyKey") JavaScript: vValue = oMap.get(vKey) [MAJOR WARNING: gets property, not key: vValue = oMap["MyKey"]] Kotlin: vValue = oMap["MyKey"] PHP: $vValue = $oMap["MyKey"] Python: vValue = oDict["MyKey"] R: vValue = oMap["MyKey"] Ruby: vValue = oMap["MyKey"] Rust: vValue = oMap.get("MyKey").cloned().unwrap() [also: vValue = oMap["MyKey"]] Scala: vValue = oMap.get("MyKey").get [also: vValue = oMap("MyKey")] SQL (MySQL): SELECT v FROM MyTable WHERE k='MyKey' SQL (PostgreSQL): SELECT v FROM MyTable WHERE k='MyKey' SQL (SQLite): SELECT v FROM MyTable WHERE k=='MyKey' Swift: vValue = oDict["MyKey"] UFL: Map.Get [or Map[Key]/Map.GetKeyValue][map get key value (dynamic key name)] AutoHotkey: vValue := oMap[vKey] [also: vValue := oMap.Get(vKey)] [note: non-existent key: oMap[] and oMap.Get() throw] C++: vValue = oMap.at(vKey) [also: vValue = oMap[vKey]] [note: 'at' throws if key doesn't exist] [WARNING: oMap[vKey]: if vKey doesn't exist, 'vValue = oMap[vKey]' creates a key with the default value, e.g. 0/""] C#: vValue = oDict[vKey] [note: non-existent key: throws] Crystal: vValue = oMap[vKey] [note: non-existent key: throws] [also (non-existent key: returns nil): vValue = oMap[vKey]?] Excel: ___ Excel VBA: vValue = oColl.Item(vKey) [also: oColl.Item(vIndex) / oColl(vKey) / oColl(vIndex)] [note: non-existent key: throws] [WARNING: it is not possible to get a list of a collection's key names] Go: vValue := oMap[vKey] [also: vValue, vHasKey := oMap[vKey]] [WARNING: non-existent key: returns default value (e.g. 0/"")] Java: vValue = oMap.get(vKey) [note: non-existent key: returns null] JavaScript: vValue = oMap.get(vKey) [note: non-existent key: returns undefined] [MAJOR WARNING: gets property, not key: vValue = oMap[vProp]] Kotlin: oOpt = oMap[vKey] [also: oOpt = oMap.get(vKey)] [note: non-existent key: returns null] [note: oMap[vKey] returns a nullable, oArray[vKey] returns a non-nullable (unless it's an array of nullables)] [e.g. vIsNull = (oOpt == null)] [e.g. vValue = oOpt!!] PHP: $vValue = $oMap[$vKey] [note: non-existent key: returns NULL] Python: vValue = oDict[vKey] [note: non-existent key: throws] R: vValue = unname(oMap[vKey]) [note: non-existent key: returns NA] Ruby: vValue = oMap[vKey] [note: non-existent key: returns nil] Rust: vValue = oMap.get(vKey).cloned().unwrap() [also: vValue = oMap[vKey]] Scala: vValue = oMap.get(vKey).get [note: non-existent key: get() returns None] [also: vValue = oMap(vKey)] SQL (MySQL): SELECT v FROM MyTable WHERE k=MyKey SQL (PostgreSQL): SELECT v FROM MyTable WHERE k=MyKey SQL (SQLite): SELECT v FROM MyTable WHERE k==MyKey Swift: vValue = oDict[vKey]! [note: non-existent key: throws] UFL: Map.GetOrDefault [if key non-existent/null, provide default (deviations from this are noted)][see also: Array.GetOrDefault] AutoHotkey: vValue := oMap.Get(vKey, vDefault) C++: ___ C#: vValue = oDict.GetValueOrDefault(vKey, vDefault) [WARNING: returns null if value is null] [note: if default omitted, the defaults for int/double/string are 0/0/"" respectively] [also: oDict[vKey] ?? vDefault] [WARNING: oDict[vKey] throws if key doesn't exist] Crystal: vValue = oMap.fetch(vKey, vDefault) Excel: ___ Excel VBA: ___ Go: ___ Java: vValue = oMap.getOrDefault(vKey, vDefault) [WARNING: returns null if value is null] [also (appears to give the same results, except it returns default rather than null): Optional.ofNullable(oMap.get(vKey)).orElse(vDefault)] [requires (Optional): import java.util.*] JavaScript: vValue = oMap.get(vKey) ?? vDefault [note: returns default if value is null/undefined] Kotlin: vValue = oMap.getOrElse(vKey, oFunc) [e.g. oMap.getOrElse(vKey){vDefault}] [e.g. oMap.getOrElse(vKey, {vDefault})] [note (unlike arrays): returns default if value is null] [also (appears to give the same results): oMap[vKey] ?: vDefault] [note: oMap[vKey] returns null if key doesn't exist] PHP: $vValue = $oMap[$vKey] ?? $vDefault Python: vValue = oDict.get(vKey, vDefault) [WARNING: returns None if value is None] R: ___ [can use: vValue = na.omit(c(oMap[vKey], vDefault))[1]] [note: 1-based] Ruby: vValue = oMap.fetch(vKey, vDefault) Rust: vValue = oMap.get(vKey).cloned().unwrap_or(vDefault) Scala: vValue = oMap.getOrElse(vKey, vDefault) SQL (MySQL): ___ [e.g. SELECT coalesce((SELECT v FROM MyTable WHERE k=MyKey AND v IS NOT NULL), MyDefault)] SQL (PostgreSQL): ___ [e.g. SELECT coalesce((SELECT v FROM MyTable WHERE k=MyKey AND v IS NOT NULL), MyDefault)] SQL (SQLite): ___ [e.g. SELECT coalesce((SELECT v FROM MyTable WHERE k==MyKey AND v IS NOT NULL), MyDefault)] Swift: vValue = oDict[vKey, default:vDefault] [WARNING: returns optional nil if value is optional nil] [also: vValue = oDict[vKey] ?? vDefault] [note: both approaches appear to give the same results] [note (both): returns default if key doesn't exist] [note: oDict[vKey] returns nil if key doesn't exist] UFL: (Map.SetDemo) [map set key value (fixed key name)] AutoHotkey: oMap["MyKey"] := "MyValue" C++: oMap["MyKey"] = "MyValue" C#: oDict["MyKey"] = "MyValue" Crystal: oMap["MyKey"] = "MyValue" Excel: ___ Excel VBA: Call oColl.Add("MyValue", "MyKey") Go: oMap["MyKey"] = "MyValue" Java: oMap.put("MyKey", "MyValue") JavaScript: oMap.set("MyKey", "MyValue") [MAJOR WARNING: sets property, not key: oMap["MyKey"] = "MyValue"] Kotlin: oMap["MyKey"] = "MyValue" PHP: $oMap["MyKey"] = "MyValue" Python: oDict["MyKey"] = "MyValue" R: oMap["MyKey"] = "MyValue" Ruby: oMap["MyKey"] = "MyValue" Rust: oMap.insert("MyKey", "MyValue") Scala: oMap("MyKey") = "MyValue" [also: oMap.put("MyKey", "MyValue")] SQL (MySQL): UPDATE MyTable SET v='MyValue' WHERE k='MyKey' SQL (PostgreSQL): UPDATE MyTable SET v='MyValue' WHERE k='MyKey' SQL (SQLite): UPDATE MyTable SET v='MyValue' WHERE k=='MyKey' Swift: oDict["MyKey"] = "MyValue" UFL: Map.Set [or Map[Key]][map set key value (dynamic key name)] AutoHotkey: oMap[vKey] := vValue [also: oMap.Set(vKey, vValue)] C++: oMap[vKey] = vValue [WARNING: oMap.insert({vKey,vValue}) *doesn't* overwrite keys] C#: oDict[vKey] = vValue Crystal: oMap[vKey] = vValue Excel: ___ Excel VBA: Call oColl.Add(vValue, vKey) [WARNING: value then key] [WARNING: key names are *case-insensitive* strings] [note: key names are optional, however, every key has a 1-based index] [note: to 'modify' a value you use Remove then Add (the key order can be maintained via Add's Before/After params)] Go: oMap[vKey] = vValue Java: oMap.put(vKey, vValue) JavaScript: oMap.set(vKey, vValue) [MAJOR WARNING: sets property, not key: oMap[vProp] = vValue] Kotlin: oMap[vKey] = vValue [also: oMap.set(vKey, vValue)] [also: oMap.put(vKey, vValue)] PHP: $oMap[$vKey] = $vValue Python: oDict[vKey] = vValue [also: oMap.update({vKey:vValue})] [WARNING: oMap.setdefault(vKey, vValue) *doesn't* overwrite keys] R: oMap[vKey] = vValue Ruby: oMap[vKey] = vValue Rust: oMap.insert(vKey, vValue) [note: insert() can both add and modify keys] [WARNING: oMap[vKey] syntax can be used to read keys, but not add/modify them] Scala: oMap(vKey) = vValue [also: oMap.put(vKey, vValue)] SQL (MySQL): UPDATE MyTable SET v=MyValue WHERE k=MyKey [also (update all rows): UPDATE MyTable SET v=(CASE WHEN k=MyKey THEN MyValue ELSE v END)] SQL (PostgreSQL): UPDATE MyTable SET v=MyValue WHERE k=MyKey [also (update all rows): UPDATE MyTable SET v=(CASE WHEN k=MyKey THEN MyValue ELSE v END)] SQL (SQLite): UPDATE MyTable SET v=MyValue WHERE k==MyKey [also (update all rows): UPDATE MyTable SET v=(CASE WHEN k==MyKey THEN MyValue ELSE v END)] Swift: oDict[vKey] = vValue UFL: Map.ForcePush [a map of arrays: append an item to an array, create the array if it doesn't exist][workaround: specify 'new array' as the default value][WARNING: no obvious function name for this, perhaps a better name exists, we're pushing to a key, not to the object itself][see also: Map.Default] AutoHotkey: ___ C++: oMap[vKey].push_back(vValue) [beforehand: std::map<std::string,std::vector<std::string>> oMap] [requires: #include <vector>] [requires: #include <map>] [WARNING: if vKey doesn't exist, 'oMap[vKey]' creates a key with the default value, e.g. an empty vector] C#: ___ Crystal: (oMap[vKey] ||= [] of String) << vValue [beforehand: oMap = {} of String=>Array(String)] [WARNING: a||=b equivalent to a?a:a=b not a=a||b] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: oMap.getOrPut(vKey, ::mutableListOf) += vValue [beforehand: oMap = mutableMapOf<String, MutableList<String>>()] PHP: $oMap[$vKey][] = $vValue [beforehand: $oMap = []] [WARNING: '$oMap[$vKey][] = $vValue' creates an array if it doesn't exist, and pushes] Python: ___ R: ___ Ruby: (oMap[vKey] ||= []) << vValue [beforehand: oMap = {}] [WARNING: a||=b equivalent to a?a:a=b not a=a||b] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Map.Fill) [or Map.SetAll][set all keys to the same value] AutoHotkey: ___ C++: ___ [can use: for (auto& [_,v] : oMap) v = vValue] [also: std::for_each(oMap.begin(), oMap.end(), [&](auto &p){p.second = vValue;})] [also: std::ranges::fill and std::ranges::views::values] C#: ___ [can use: foreach (var k in oDict.Keys.ToList()) oDict[k] = vValue] [also: oDict.Keys.ToList().ForEach(k=>oDict[k]=vValue)] Crystal: oMap.transform_values!{|v| vValue} [note: omit '!' to return a new map] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var oEntry : oMap.entrySet()) {oMap.put(oEntry.getKey(), vValue);}] JavaScript: ___ [can use: [...oMap.keys()].forEach(k=>oMap.set(k, vValue))] Kotlin: oMap.replaceAll{_,_ -> vValue} PHP: ___ [can use: foreach ($oMap as $k=>$v) $oMap[$k] = $vValue] Python: ___ [can use: for k,v in oDict.items(): oDict[k] = vValue] R: oMap[] = vValue [note: leaves names ('keys') unchanged] Ruby: oMap.transform_values!{|v| vValue} [note: omit '!' to return a new map] Rust: for v in oMap.values_mut() {*v = vValue;} Scala: ___ [can use: for ((k,v) <- oMap) oMap(k) = vValue] SQL (MySQL): UPDATE MyTable SET v=MyValue SQL (PostgreSQL): UPDATE MyTable SET v=MyValue SQL (SQLite): UPDATE MyTable SET v=MyValue Swift: ___ [can use: for (k,_) in oDict {oDict[k] = vValue}] UFL: Map.Swap [swap 2 elements] AutoHotkey: ___ C++: std::swap(oMap[vKey1], oMap[vKey2]) [also: std::swap(oMap.at(vKey1), oMap.at(vKey2))] [WARNING: if vKey doesn't exist, 'oMap[vKey]' creates a key with the default value, e.g. 0/""] C#: (oDict[vKey1], oDict[vKey2]) = (oDict[vKey2], oDict[vKey1]) [note: destructuring assignment] Crystal: oMap[vKey1], oMap[vKey2] = oMap[vKey2], oMap[vKey1] [note: destructuring assignment] Excel: ___ Excel VBA: ___ Go: oMap[vKey1], oMap[vKey2] = oMap[vKey2], oMap[vKey1] [note: destructuring assignment] Java: ___ JavaScript: ___ Kotlin: ___ PHP: [$oMap[$vKey1], $oMap[$vKey2]] = [$oMap[$vKey2], $oMap[$vKey1]] [note: destructuring assignment] Python: oDict[vKey1], oDict[vKey2] = oDict[vKey2], oDict[vKey1] [note: destructuring assignment] R: ___ Ruby: oMap[vKey1], oMap[vKey2] = oMap[vKey2], oMap[vKey1] [note: destructuring assignment] Rust: ___ Scala: oMapNew = oMap.clone.addOne(vKey1, oMap(vKey2)).addOne(vKey2, oMap(vKey1)) [deprecated: oMapNew = oMap.updated(vKey1, oMap(vKey2)).updated(vKey2, oMap(vKey1))] SQL (MySQL): UPDATE MyTable SET k=if(k=MyKey1,MyKey2,MyKey1) WHERE k IN (MyKey1,MyKey2) [also: UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 ELSE MyKey1 END) WHERE k IN (MyKey1,MyKey2)] [also (update all rows): UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 WHEN k=MyKey2 THEN MyKey1 ELSE k END)] SQL (PostgreSQL): UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 ELSE MyKey1 END) WHERE k IN (MyKey1,MyKey2) [also (update all rows): UPDATE MyTable SET k=(CASE WHEN k=MyKey1 THEN MyKey2 WHEN k=MyKey2 THEN MyKey1 ELSE k END)] SQL (SQLite): UPDATE MyTable SET k=iif(k==MyKey1,MyKey2,MyKey1) WHERE k IN (MyKey1,MyKey2) [also: UPDATE MyTable SET k=(CASE WHEN k==MyKey1 THEN MyKey2 ELSE MyKey1 END) WHERE k IN (MyKey1,MyKey2)] [also (update all rows): UPDATE MyTable SET k=(CASE WHEN k==MyKey1 THEN MyKey2 WHEN k==MyKey2 THEN MyKey1 ELSE k END)] Swift: (oDict[vKey1], oDict[vKey2]) = (oDict[vKey2], oDict[vKey1]) [note: destructuring assignment] [note: swap() fails with 'overlapping accesses' error: swap(&oDict[vKey1], &oDict[vKey2])] UFL: Map.Delete [delete a key][see also: VarDelete] AutoHotkey: oMap.Delete(vKey) C++: oMap.erase(vKey) C#: oDict.Remove(vKey) Crystal: oMap.delete(vKey) Excel: ___ Excel VBA: oColl.Remove(vKey) [also: oColl.Remove(vIndex)] Go: delete(oMap, vKey) Java: oMap.remove(vKey) JavaScript: oMap.delete(vKey) Kotlin: oMap.remove(vKey) PHP: $oMap[$vKey] = null [also: unset($oMap[$vKey])] Python: del oDict[vKey] [also: oDict.pop(vKey) and oDict.popitem(vKey)] R: oMapNew = oMap[names(oMap) != vKey] Ruby: oMap.delete(vKey) Rust: oMap.remove(vKey) Scala: oMap.remove(vKey) SQL (MySQL): DELETE FROM MyTable WHERE k=MyKey [also: UPDATE MyTable SET v=NULL where k=MyKey] SQL (PostgreSQL): DELETE FROM MyTable WHERE k=MyKey [also: UPDATE MyTable SET v=NULL where k=MyKey] SQL (SQLite): DELETE FROM MyTable WHERE k==MyKey [also: UPDATE MyTable SET v=NULL where k==MyKey] Swift: oDict[vKey] = nil UFL: Map.Clear [delete all keys][see also: VarDelete] AutoHotkey: oMap.Clear() [also: oMap := Map()] [deprecated (AHK v1): oMap.Delete(oMap.MinIndex(), oMap.MaxIndex()), oMap.Delete("", vKeyLast)] C++: oMap.clear() C#: oDict.Clear() Crystal: oMap.clear Excel: ___ Excel VBA: Set oColl = New Collection Go: clear(oMap) Java: oMap.clear() JavaScript: oMap.clear() Kotlin: oMap.clear() PHP: $oMap = [] [also: array_splice($oMap, 0, count($oMap))] [note: appears to work even if the map has no '0' key] Python: oDict.clear() R: oMap = head(oMap, 0) Ruby: oMap.clear Rust: oMap.clear() Scala: oMap.clear SQL (MySQL): DELETE FROM MyTable SQL (PostgreSQL): DELETE FROM MyTable SQL (SQLite): DELETE FROM MyTable Swift: oDict.removeAll() UFL: Map.Clone [or Map.Copy][copy the entire map] AutoHotkey: oMapNew := oMap.Clone() C++: std::map<std::string,std::string> oMapNew = oMap [WARNING: this creates a copy, not a reference] C#: var oDictNew = new Dictionary<string,string>(oDict) Crystal: oMapNew = oMap.clone Excel: ___ Excel VBA: ___ [note: 'Set oCollNew = oColl' creates a reference, unlike arrays, where 'Set oArrayNew = oArray' is invalid, and 'oArrayNew = oArray' clones the array] Go: ___ [WARNING: Go maps lack a clone method] Java: var oMapNew = new LinkedHashMap<>(oMap) JavaScript: oMapNew = new Map(oMap) Kotlin: oMapNew = oMap.toMutableMap() [also: oMapNew = oMap.toMap()] PHP: $oMapNew = $oMap [WARNING: this creates a copy, not a reference] Python: oDictNew = oDict.copy() R: oMapNew = oMap [WARNING: this creates a copy, not a reference] Ruby: oMapNew = oMap.clone Rust: oMapNew = oMap.clone() [WARNING: this creates a copy, not a reference: oMapNew = oMap] [WARNING: Rust makes a distinction between clone and copy] Scala: oMapNew = oMap.clone SQL (MySQL): CREATE TABLE MyTableNew AS SELECT * FROM MyTable SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT * FROM MyTable SQL (SQLite): CREATE TABLE MyTableNew AS SELECT * FROM MyTable Swift: oDictNew = oDict [WARNING: this creates a copy, not a reference] UFL: Map.FromEntries [or Entries.ToMap][create a map from an array of entries, each entry is an array containing a key and a value][e.g. 'oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]]'] AutoHotkey: ___ C++: ___ [e.g. oMap.insert({{"k1","v1"}, {"k2","v2"}, {"k3","v3"}})] [e.g. oMap.insert(oEntries.begin(), oEntries.end())] [beforehand: std::map<std::string,std::string> oMap] [beforehand (also): std::pair<std::string,std::string> oEntries[] = {{"k1","v1"}, {"k2","v2"}, {"k3","v3"}}] C#: var oDict = oEntries.ToDictionary(e=>e[0], e=>e[1]) [requires (ToDictionary): using System.Linq] Crystal: oMap = oEntries.to_h [e.g. oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]]] Excel: ___ Excel VBA: ___ Go: ___ Java: LinkedHashMap<String,String> oMap = Arrays.stream(oEntries).collect(LinkedHashMap::new, (a,e)->a.put(e[0],e[1]), Map::putAll) [also: for (String[] e : oEntries) oMap.put(e[0], e[1])] [e.g. LinkedHashMap<String,String> oMap = new LinkedHashMap<>()] [e.g. String[][] oEntries = {{"k1","v1"},{"k2","v2"},{"k3","v3"}}] [also: Map<String,String> oMap = IntStream.range(0, oEntries.length).boxed().collect(Collectors.toMap(i->oEntries[i][0], i->oEntries[i][1]))] [requires (Collectors): import java.util.stream.*] JavaScript: oMap = new Map(oEntries) Kotlin: oMap = oEntries.map{Pair(it[0],it[1])}.toMap() [also: oMap = oEntries.map{e->Pair(e[0],e[1])}.toMap()] [e.g. oEntries = arrayOf(arrayOf("k1","v1"), arrayOf("k2","v2"), arrayOf("k3","v3"))] [also: oMap = oEntriesPairs.toMap()] [e.g. oEntriesPairs = arrayOf(Pair("k1", "v1"), Pair("k2", "v2"), Pair("k3", "v3"))] PHP: array_reduce($oEntries, function($vAccum, $oEntry) use (&$oMap) {$oMap[$oEntry[0]] = $oEntry[1];}) [beforehand: $oMap = []] Python: oDict = dict(oEntries) R: oMap = setNames(sapply(oEntries, "[[", 2), sapply(oEntries, "[[", 1)) [e.g. oEntries = Map(c, c("k1","k2","k3"), c("v1","v2","v3"), USE.NAMES=FALSE)] Ruby: oMap = oEntries.to_h [e.g. oEntries = [["k1","v1"], ["k2","v2"], ["k3","v3"]]] Rust: oMap = HashMap::from(oEntries) [e.g. oEntries = [("k1","v1"), ("k2","v2"), ("k3","v3")]] [also: oMap = oEntriesVec.clone().into_iter().collect::<HashMap<_,_>>()] [e.g. oEntriesVec: Vec<_> = vec![("k1","v1"), ("k2","v2"), ("k3","v3")]] Scala: oMap = oEntries.toMap [e.g. specify map type: scala.collection.mutable.LinkedHashMap.from(oEntries)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oDict = Dictionary(uniqueKeysWithValues:oEntries.map{($0[0],$0[1])}) [note: failed with $0 and $1] UFL: Map.FromFlatEntries [create a map from an array of alternating keys/values][e.g. 'oFlatEntries = ["k1","v1", "k2","v2", "k3","v3"]'][see also: Array.Chunk/Map.FromEntries/Array.Zip/Array.GroupBy/Array.FilterGetEveryNth] AutoHotkey: oMap := Map(oFlatEntries*) C++: ___ C#: oDict = oFlatEntries.Chunk(2).ToDictionary(e=>e[0], e=>e[1]) [requires (ToDictionary): using System.Linq] Crystal: oMap = oFlatEntries.each_slice(2).to_h Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oMap = new Map(Array(oFlatEntries.length/2).fill().map((v,k)=>oFlatEntries.slice(k*2, k*2+2))) Kotlin: oMap = oFlatEntries.toList().chunked(2).map{Pair(it[0],it[1])}.toMap() PHP: array_reduce(array_chunk($oFlatEntries, 2), function($vAccum, $oEntry) use (&$oMap) {$oMap[$oEntry[0]] = $oEntry[1];}) [beforehand: $oMap = []] Python: oDict = dict(itertools.batched(oFlatEntries, 2)) [requires: import itertools] [also: oDict = dict([oFlatEntries[i:i+2] for i in range(0, len(oFlatEntries), 2)])] R: oMap = setNames(oVec[c(F, T)], oVec[c(T, F)]) [note: can use TRUE/FALSE instead of T/F] Ruby: oMap = oFlatEntries.each_slice(2).to_h Rust: oMap = oFlatEntries.chunks(2).map(|e| (e[0],e[1])).collect::<HashMap<_,_>>() Scala: oMap = oArray.grouped(2).map(v=>(v(0),v(1))).toMap [e.g. specify map type: scala.collection.mutable.LinkedHashMap.from(oEntries)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oDict = Dictionary(uniqueKeysWithValues:zip(oTemp[0]!, oTemp[1]!)) [beforehand: var oTemp = Dictionary(grouping:oFlatEntries.enumerated(), by:{$0.0%2}).mapValues{$0.map{$0.element}}] [also (approach 2): oDict = Dictionary(uniqueKeysWithValues:oEntries.map{($0[0],$0[1])})] [beforehand (approach 2): oEntries = stride(from:0, to:oFlatEntries.count, by:2).map{Array(oFlatEntries[$0..<min($0+2, oFlatEntries.count)])}] UFL: Map.FromTwoArrays [or Map.FromKeysValues][create a map by combining a key array and a value array (of equal length)][see also: Array.Zip] AutoHotkey: ___ C++: ___ [can use: std::map::insert() multiple times] C#: var oDict = oKeys.Zip(oValues, (k,v)=>new{k,v}).ToDictionary(e=>e.k, e=>e.v) [also: var oDict = Enumerable.Range(0, oKeys.Length).ToDictionary(i=>oKeys[i], i=>oValues[i])] [requires (Enumerable/GroupBy/Zip): using System.Linq] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: oMap = oKeys.zip(oValues).to_h Excel: ___ Excel VBA: ___ Go: ___ Java: Map<String,String> oMap = IntStream.range(0, oKeys.length).boxed().collect(Collectors.toMap(i->oKeys[i], i->oValues[i])) [requires (Collectors): import java.util.stream.*] JavaScript: oMap = new Map(oKeys.map((v,k)=>[v,oValues[k]])) [note: where v is a key name, and k is an array index] Kotlin: oMap = oKeys.zip(oValues).toMap() PHP: $oMap = array_combine($oKeys, $oValues) Python: oDict = dict(zip(oKeys, oValues)) R: oMap = setNames(oValues, oKeys) Ruby: oMap = oKeys.zip(oValues).to_h Rust: oMap = oKeys.into_iter().zip(oValues.into_iter()).collect::<HashMap<_,_>>() [also (loop): for (k,v) in oKeys.into_iter().zip(oValues.into_iter()) {oMap.insert(k,v);}] [beforehand (loop): let mut oMap: HashMap<&str,&str> = HashMap::new()] [e.g. oKeys = ["k1", "k2", "k3"]] [e.g. oValues = ["v1", "v2", "v3"]] Scala: oMap = oArray1.zip(oArray2).toMap [e.g. specify map type: scala.collection.mutable.LinkedHashMap.from(oEntries)] SQL (MySQL): SELECT t1.v,t2.v FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.k = t2.k [note (JOIN): puts 2 columns side-by-side, uses an ON clause to specify a column in common] SQL (PostgreSQL): SELECT t1.v,t2.v FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.k = t2.k [note (JOIN): puts 2 columns side-by-side, uses an ON clause to specify a column in common] [note: use FULL OUTER JOIN, instead of INNER JOIN, to also list unmatched rows] SQL (SQLite): SELECT t1.v,t2.v FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.k == t2.k [note (JOIN): puts 2 columns side-by-side, uses an ON clause to specify a column in common] [note: use FULL OUTER JOIN, instead of INNER JOIN, to also list unmatched rows] Swift: oDict = Dictionary(uniqueKeysWithValues:zip(oKeys, oValues)) UFL: Map.SetMultOverwriteMap [map overwrite/combine/merge, overwrite/add values, based on another map][see also: Map.ForEach/Map.FromEntries] AutoHotkey: ___ [can use (replace ';' with LF): for vKey, vValue in oMapAddIn; oMap[vKey] := vValue] C++: ___ [can use: for (const auto& [vKey, vValue] : oMapAddIn) oMap[vKey] = vValue] C#: ___ [can use: foreach (var e in oDictAddIn) oDict[e.Key] = e.Value] Crystal: oMap.merge!(oMapAddIn) [note: in Crystal, update() modifies 1 key based on a function, it doesn't merge 2 maps] Excel: ___ Excel VBA: ___ Go: maps.Copy(oMap, oMapAddIn) Java: oMap.putAll(oMapAddIn) JavaScript: oMap = new Map([...oMap, ...oMapAddIn, ...oMapAddIn2]) Kotlin: oMap += oMapAddIn [WARNING: unlike PHP, this overwrites keys] PHP: $oMap = array_replace($oMap, $oMapAddIn, $oMapAddIn2) [also: $oMap = array_merge($oMap, $oMapAddIn, $oMapAddIn2)] [note: array_replace treats all key names consistently, array_merge uses special handling for numeric keys] Python: oDict.update(oDictAddIn) [also: oDict |= oDictAddIn] [also: oDict = {**oDict, **oDictAddIn, **oDictAddIn2}] R: ___ [can use: oMap[names(oMapAddIn)] = oMapAddIn] [e.g. oMap = c("k1"="v1", "k2"="v2", "k3"="v3")] Ruby: oMap.update(oMapAddIn) [alias (update): merge] Rust: oMap.extend(oMapAddIn.clone()) Scala: oMap.addAll(oMapAddIn) SQL (MySQL): SELECT * FROM MyTable2 UNION SELECT * FROM MyTable1 WHERE k NOT IN (SELECT k FROM MyTable2) SQL (PostgreSQL): SELECT * FROM MyTable2 UNION SELECT * FROM MyTable1 WHERE k NOT IN (SELECT k FROM MyTable2) SQL (SQLite): SELECT * FROM MyTable2 UNION SELECT * FROM MyTable1 WHERE k NOT IN (SELECT k FROM MyTable2) Swift: oDict = oDict.merging(oDictAddIn){_,v2 in v2} [note: '{_,v2 in v2}': it receives 2 values (old and new) and returns 1] UFL: Map.SetMultOverwriteEntries [map overwrite/combine/merge, overwrite/add values, based on entries (key-value pairs)][see also: Map.FromEntries] AutoHotkey: ___ [can use: oMap.Set(vKey1,vValue1, vKey2,vValue2, vKey3,vValue3)] [can use (replace ';' with LF): for _, oEntry in oEntries; oMap[oEntry[1]] := oEntry[2]] C++: ___ [can use: for (const auto& [vKey, vValue] : oEntries) oMap[vKey] = vValue] C#: ___ [can use: foreach (var e in oEntries) oDict[e[0]] = e[1]] Crystal: oMap.merge!(oEntries.to_h) [note: in Crystal, update() modifies 1 key based on a function, it doesn't merge 2 maps] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var e : oEntries) oMap.put(e[0], e[1])] JavaScript: oMap = new Map([...oMap, ...oEntries]) Kotlin: ___ [can use: for (oEntry in oEntries) oMap[oEntry[0]] = oEntry[1]] PHP: ___ [can use: foreach ($oEntries as $e) $oMap[$e[0]] = $e[1]] Python: oDict.update(oEntries) R: ___ Ruby: oMap.update(oEntries.to_h) [alias (update): merge] Rust: ___ [can use: for [vKey, vValue] in &oEntries {oMap.insert(vKey, vValue);}] Scala: oMap.addAll(oEntries) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: for e in oEntries {oDict[e[0]] = e[1]}] UFL: Map.SetMultSkipExistMap [or Map.SetMultIfAbsent/Map.SetMultNoOverwrite][map combine, add values, if the key doesn't already exist, based on another map (add only, don't overwrite) (maintain original values)][see also: Map.ForEach/Map.FromEntries] AutoHotkey: ___ [can use (replace ';' with LF): for vKey, vValue in oMapAddIn; if !oMap.Has(vKey); oMap[vKey] := vValue] C++: ___ [can use: for (const auto& [vKey, vValue] : oMapAddIn) oMap.insert({vKey,vValue})] [WARNING: insert() *doesn't* overwrite keys] C#: ___ [can use: foreach (var e in oDictAddIn) if (!oDict.ContainsKey(e.Key)) oDict[e.Key] = e.Value] Crystal: oMap.merge!(oMapAddIn){|k,v1,v2| v1} [note: in Crystal, update() modifies 1 key based on a function, it doesn't merge 2 maps] Excel: ___ Excel VBA: ___ Go: ___ Java: oMapAddIn.forEach(oMap::putIfAbsent) JavaScript: ___ [can use: oMapAddIn.forEach((v,k)=>!oMap.has(k) && oMap.set(k,v))] Kotlin: oMap += oMapAddIn - oMap.keys PHP: $oMap += $oMapAddIn [note: unlike Kotlin, this *doesn't* overwrite keys] Python: ___ [can use: oDictCopy = oDict.copy(); oDict.update(oDictAddIn); oDict.update(oDictCopy)] [can use (replace ';' with LF): for vKey, vValue in oDictAddIn.items():; if vKey not in oDict:; oDict[vKey] = vValue] R: ___ Ruby: oMap.update(oMapAddIn){|k,v1,v2| v1} [alias (update): merge] Rust: ___ [can use: for (vKey, vValue) in &oMapAddIn {if !oMap.contains_key(vKey) {oMap.insert(vKey, vValue);}}] Scala: oMapAddIn.foreach((k,v)=>oMap.getOrElseUpdate(k,v)) SQL (MySQL): SELECT * FROM MyTable1 UNION SELECT * FROM MyTable2 WHERE k NOT IN (SELECT k FROM MyTable1) SQL (PostgreSQL): SELECT * FROM MyTable1 UNION SELECT * FROM MyTable2 WHERE k NOT IN (SELECT k FROM MyTable1) SQL (SQLite): SELECT * FROM MyTable1 UNION SELECT * FROM MyTable2 WHERE k NOT IN (SELECT k FROM MyTable1) Swift: oDict = oDict.merging(oDictAddIn){v1,_ in v1} [note: '{v1,_ in v1}': it receives 2 values (old and new) and returns 1] UFL: Map.SetMultSkipExistEntries [or Map.SetMultIfAbsent/Map.SetMultNoOverwrite][map combine, add values, if the key doesn't already exist, based on entries (key-value pairs) (add only, don't overwrite) (maintain original values)][see also: Map.FromEntries] AutoHotkey: ___ [can use (replace ';' with LF): for _, oEntry in oEntries; if !oMap.Has(oEntry[1]); oMap[oEntry[1]] := oEntry[2]] C++: ___ [e.g. oMap.insert({{"k1","v1"}, {"k2","v2"}, {"k3","v3"}})] [e.g. oMap.insert(oEntries.begin(), oEntries.end())] [WARNING: insert() *doesn't* overwrite keys] C#: ___ [can use: foreach (var e in oEntries) if (!oDict.ContainsKey(e[0])) oDict[e[0]] = e[1]] Crystal: oMap.merge!(oEntries.to_h){|k,v1,v2| v1} [note: in Crystal, update() modifies 1 key based on a function, it doesn't merge 2 maps] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var e : oEntries) if (!oMap.containsKey(e[0])) oMap.put(e[0], e[1])] JavaScript: ___ [can use: oEntries.forEach(e=>!oMap.has(e[0]) && oMap.set(...e))] Kotlin: ___ [can use: for (oEntry in oEntries) if (!oMap.contains(oEntry[0])) oMap[oEntry[0]] = oEntry[1]] PHP: ___ [can use: foreach ($oEntries as $e) !array_key_exists($e[0], $oMap) && $oMap[$e[0]] = $e[1]] Python: ___ [can use: oDictCopy = oDict.copy(); oDict.update(oEntries); oDict.update(oDictCopy)] [can use (replace ';' with LF): for oEntry in oEntries:; if oEntry[0] not in oDict:; oDict[oEntry[0]] = oEntry[1]] R: ___ Ruby: oMap.update(oEntries.to_h){|k,v1,v2| v1} [alias (update): merge] Rust: ___ [can use: for [vKey, vValue] in &oEntries {if !oMap.contains_key(vKey) {oMap.insert(vKey, vValue);}}] Scala: oEntries.foreach((k,v)=>oMap.getOrElseUpdate(k,v)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [can use: for e in oEntries {if (!oDict.keys.contains(e[0])) {oDict[e[0]] = e[1]}}] UFL: Map.Flip [flip keys/values][assumes no duplicates amongst values][see also: Array.Zip/Map.MapValues] AutoHotkey: ___ [can use (replace ';' with LF): oMapNew := Map(); for vKey, vValue in oMap; oMapNew[vValue] := vKey] C++: for (auto e = oMap.begin(); e != oMap.end(); ++e) oMapNew[e->second] = e->first [beforehand: std::map<std::string,std::string> oMapNew] C#: oDictNew = oDict.ToDictionary(e=>e.Value, e=>e.Key) [requires (ToDictionary): using System.Linq] Crystal: oMapNew = oMap.invert Excel: ___ Excel VBA: ___ Go: ___ Java: for (var e : oMap.entrySet()) oMapNew.put(e.getValue(), e.getKey()) [beforehand: LinkedHashMap<String,String> oMapNew = new LinkedHashMap<>()] [also: var oMapNew = oMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))] [requires (Collectors): import java.util.stream.*] JavaScript: oMapNew = new Map(Array.from(oMap, e=>e.reverse())) [also: oMapNew = new Map(Array.from(oMap, ([k,v])=>[v,k]))] Kotlin: oMapNew = oMap.map{(k,v)->v to k}.toMap() PHP: $oMapNew = array_flip($oMap) Python: oDictNew = {v:k for k,v in oDict.items()} [also: oDictNew = dict((v,k) for k,v in oDict.items())] [also: oDictNew = dict(zip(oDict.values(), oDict.keys()))] R: oMapNew = setNames(names(oMap), unname(oMap)) [note: setNames param order: values then keys] Ruby: oMapNew = oMap.invert Rust: oMapNew: HashMap::<_,_> = oMap.iter().map(|(k,v)| (v,k)).collect() Scala: oMapNew = oMap.map(_.swap) [note: preserves map type] SQL (MySQL): ___ [can use: UPDATE MyTable t1, MyTable t2 SET t1.k=t1.v, t1.v=t2.k WHERE t1.k=t2.k] [note: swaps 2 columns] [MAJOR WARNING: the 'SET k=v, v=k' approach fails in MySQL] SQL (PostgreSQL): UPDATE MyTable SET k=v, v=k [note: swaps 2 columns] [note: use a WHERE clause to only modify some rows] SQL (SQLite): UPDATE MyTable SET k=v, v=k [note: swaps 2 columns] [note: use a WHERE clause to only modify some rows] Swift: oDictNew = Dictionary(uniqueKeysWithValues:oDict.map{($1,$0)}) UFL: Map.MultiFlip [or Map.FlipMulti][flip keys/values][handles duplicates amongst values][key-value pairs to key-array pairs (i.e. 'former value'-'array of former keys' pairs)] AutoHotkey: ___ [can use (replace ';' with LF): oMapNew := Map(); for k, v in oMap; if oMapNew.Has(v); oMapNew[v].Push(k); else; oMapNew[v] := [k]] C++: for (const auto& [k, v] : oMap) oMapNew[v].push_back(k) [beforehand: std::map<std::string,std::vector<std::string>> oMapNew] [requires: #include <vector>] [requires: #include <map>] [WARNING: if k doesn't exist, 'oMap[k]' creates a key with the default value, e.g. an empty vector] C#: oDictNew = oDict.GroupBy(e=>e.Value).ToDictionary(g=>g.Key, g=>g.Select(e=>e.Key).ToArray()) [requires (GroupBy/Select/ToDictionary): using System.Linq] Crystal: oMapNew = oMap.each_with_object({} of String=>Array(String)){|(k,v),o| (o[v]||=[] of String)<<k} [WARNING: a||=b equivalent to a?a:a=b not a=a||b] [also: oMapNew = oMap.each_with_object({} of String=>Array(String)){|(k,v),o| o.has_key?(v) ? o[v]<<k : (o[v]=[k])}] Excel: ___ Excel VBA: ___ Go: ___ Java: var oMapNew = oMap.entrySet().stream().collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()))) [requires (Collectors): import java.util.stream.*] JavaScript: for (const [k,v] of oMap) oMapNew.has(v) ? oMapNew.get(v).push(k) : oMapNew.set(v, [k]) [beforehand: oMapNew = new Map()] Kotlin: oMapNew = oMap.entries.groupBy({it.value}, {it.key}) [also: oMapNew = oMap.toList().groupBy{it.second}.mapValues{it.value.map{it.first}}] PHP: foreach ($oMap as $k=>$v) $oMapNew[$v][] = $k [WARNING: '$oMap[$k][] = $v' creates an array if it doesn't exist, and pushes] [beforehand: $oMapNew = []] Python: for k,v in oDict.items(): oDictNew.setdefault(v, []).append(k) [beforehand: oDictNew = {}] [also: for k,v in oDict.items(): oDictNew[v] = oDictNew.get(v, []) + [k]] R: oList = split(oMap, unname(oMap)) [afterwards: for (k in names(oList)) oList[[k]] = names(oList[[k]])] Ruby: oMapNew = oMap.each_with_object({}){|(k,v),o| (o[v]||=[])<<k} [WARNING: a||=b equivalent to a?a:a=b not a=a||b] [also: oMapNew = oMap.each_with_object({}){|(k,v),o| o.include?(v) ? o[v]<<k : o[v]=[k]}] Rust: oMapNew: HashMap::<_,Vec<_>> = oMap.iter().fold(HashMap::new(), |mut a,e| {a.entry(e.1).or_default().push(e.0); a}) [also (loop): for (k,v) in &oMap {oMapNew.entry(v).or_default().push(k);}] [beforehand (loop): let mut oMapNew = BTreeMap::<_, Vec<_>>::new()] [requires: use std::collections::BTreeMap] Scala: oMapNew = oMap.toList.groupBy(_._2).view.mapValues(_.map(_._1)).toMap [e.g. specify map type: scala.collection.mutable.LinkedHashMap.from(oEntries)] [WARNING (all): groupBy doesn't preserve order] [e.g. preserve order: var oMapNew = scala.collection.mutable.LinkedHashMap[String,List[String]]().withDefaultValue(List[String]()); oMap.foreach((k,v)=>oMap(v):+=k)] SQL (MySQL): SELECT v AS k,group_concat(k ORDER BY k SEPARATOR ',') AS v FROM MyTable GROUP BY v SQL (PostgreSQL): SELECT v AS k,string_agg(k, ',' ORDER BY k) AS v FROM MyTable GROUP BY v SQL (SQLite): SELECT v AS k,group_concat(k, ',' ORDER BY k) AS v FROM MyTable GROUP BY v [version: SQLite 3.44: group_concat(v, MySep ORDER BY k)] [also: string_agg()] Swift: oDictNew = Dictionary(oDict.map{($1,[$0])}, uniquingKeysWith:{$0+$1}) [note: using '+' to concatenate arrays] UFL: Map.MapValues [map values: apply a function to each value][see also: Map.Flip/Map.Values/Array.Zip/Map.FromEntries] AutoHotkey: ___ C++: ___ C#: oDictNew = oDict.ToDictionary(e=>e.Key, e=>oFunc(e.Value)) [requires (ToDictionary): using System.Linq] Crystal: oMapNew = oMap.transform_values{|v| oFunc.call(v)} [also: oMapNew = oMap.transform_values(&oFunc)] Excel: ___ Excel VBA: ___ Go: ___ Java: var oMapNew = oMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e->oFunc.apply(e.getValue()))) [requires (Collectors): import java.util.stream.*] JavaScript: oMapNew = new Map(Array.from(oMap, e=>[e[0],oFunc(e[1])])) Kotlin: oMapNew = oMap.mapValues{oFunc(it)} [also: oMapNew = oMap.mapValues(oFunc)] PHP: ___ [can use: foreach ($oMap as $k=>$v) $oMapNew[$k] = $oFunc($v)] [beforehand: $oMapNew = []] Python: oDictNew = {k:oFunc(v) for k,v in oDict.items()} [also: oDictNew = dict((k,oFunc(v)) for k,v in oDict.items())] [also: oDictNew = dict(zip(oDict.keys(), map(oFunc, oDict.values())))] R: oMapNew = mapply(oFunc, oMap) Ruby: oMapNew = oMap.transform_values{|v| oFunc.call(v)} [also: oMapNew = oMap.transform_values(&oFunc)] Rust: oMapNew: HashMap::<_,_> = oMap.iter().map(|(k,v)| (k,oFunc(v.to_string()).to_string())).collect() Scala: oMapNew = oMap.view.mapValues(oFunc).toMap [also: var oMapNew = oMap.view.mapValues(oFunc(_)).toMap] [e.g. specify map type: scala.collection.mutable.LinkedHashMap.from(oEntries)] SQL (MySQL): ___ [e.g. UPDATE MyTable SET v=v*2] SQL (PostgreSQL): ___ [e.g. UPDATE MyTable SET v=v*2] SQL (SQLite): ___ [e.g. UPDATE MyTable SET v=v*2] Swift: oDictNew = oDict.mapValues{oFunc($0)} [also: oDictNew = oDict.mapValues(oFunc)] UFL: Map.KeyOf [return first key that contains value][can be used as Map.HasVal/Map.Any][see also: Array.IndexOf/Array.HasVal/Array.Any/Array.Find] AutoHotkey: ___ C++: ___ [can use: auto oIter = std::find_if(std::begin(oMap), std::end(oMap), [&](const std::pair<std::string, std::string> &pair) {return pair.second == vNeedle;})] [afterwards (is match): auto vIsMatch = (oIter != std::end(oMap))] [afterwards (get match): auto vKey = oIter->first] [requires (find_if): #include <algorithm>] C#: vKey = oDict.FirstOrDefault(e=>e.Value == vNeedle).Key Crystal: vKey = oMap.key_for(vNeedle) [note: throws if no match] Excel: ___ Excel VBA: ___ Go: ___ Java: oOpt = oMap.entrySet().stream().filter(e->e.getValue()==vNeedle).findFirst().map(Map.Entry::getKey) [note: findFirst() returns an optional, map() modifies a non-empty optional, and leaves unchanged an empty optional] [also (other languages): safe navigation operator, Rust's map_or()] JavaScript: ___ [can use: vKey = [...oMap.entries()].find(e=>e[1]==vNeedle)[0]] Kotlin: vKey = oMap.entries.find{it.value == vNeedle}?.key [note: returns null if no match] PHP: $vKey = array_search($vNeedle, $oMap) [WARNING: returns false if no match] Python: vKey = next((k for k,v in oDict.items() if v == vNeedle), None) R: vKey = names(oMap)[match(vValue, oMap)] [note: returns NA if no match] Ruby: vKey = oMap.key(vNeedle) [note: returns nil if no match] Rust: oOpt = oMap.iter().find_map(|(k,&v)| if v == vNeedle {Some(k)} else {None}) [e.g. vIsMatch = oOpt.is_some()] [e.g. vValue = oOpt.unwrap_or(vDefault)] [e.g. vValue = oOpt.unwrap()] Scala: oOptKey = oMap.find(_._2==vNeedle).map(_._1) [also: vKey = oMap.find(_._2==vNeedle).get._1] [note: find() returns an optional, map() modifies a non-empty optional, and leaves unchanged an empty optional] SQL (MySQL): SELECT min(k) FROM MyTable WHERE v=MyNeedle [note: returns NULL if no match] SQL (PostgreSQL): SELECT min(k) FROM MyTable WHERE v=MyNeedle [note: returns NULL if no match] SQL (SQLite): SELECT min(k) FROM MyTable WHERE v==MyNeedle [note: returns NULL if no match] Swift: vKey = oDict.first(where:{$0.value == vNeedle})?.key [note: returns nil if no match] UFL: (Map.Equals) [do the contents of 2 maps match (at least one level deep) (same key-value pairs)] AutoHotkey: ___ C++: vIsMatch = (oMap1 == oMap2) C#: ___ [can use: vIsMatch = (oDict1.Count == oDict2.Count) && oDict1.Keys.All(k=>oDict2.ContainsKey(k) && (oDict1[k] == oDict2[k]))] [requires (All): using System.Linq] Crystal: vIsMatch = (oMap1 == oMap2) Excel: ___ Excel VBA: ___ Go: vIsMatch := reflect.DeepEqual(oMap1, oMap2) [requires: import "reflect"] [note: '==': 'map can only be compared to nil'] Java: vIsMatch = oMap1.equals(oMap2) JavaScript: ___ [can use: vIsMatch = (oMap1.size == oMap2.size) && Array.from(oMap1.keys()).every(k=>oMap2.has(k) && (oMap1.get(k) === oMap2.get(k)))] Kotlin: vIsMatch = oMap1.equals(oMap2) [also: vIsMatch = (oMap1 == oMap2)] [note: == compares contents, === compares references] PHP: $vIsMatch = ($oMap1 === $oMap2) [note: == compares contents, === compares contents (stricter), neither compare references] Python: vIsMatch = (oDict1 == oDict2) R: vIsMatch = identical(oMap1, oMap2) Ruby: vIsMatch = (oMap1 == oMap2) Rust: vIsMatch = (oMap1 == oMap2) [also: vIsMatch = oMap1.eq(&oMap2)] Scala: vIsMatch = oMap1.equals(oMap2) [also: vIsMatch = (oMap1 == oMap2)] SQL (MySQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND 0 = (SELECT COUNT(*) FROM (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) oTemp1) AND 0 = (SELECT COUNT(*) FROM (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) oTemp2) [algorithm: the row counts match, and there are no rows unique to table 1, or table 2] [MAJOR WARNING: in MySQL, 'EXISTS' must be part of 'WHERE (NOT) EXISTS', unlike PostgreSQL/SQLite] [version: MySQL 8.0.31: EXCEPT added] SQL (PostgreSQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) [algorithm: the row counts match, and there are no rows unique to table 1, or table 2] SQL (SQLite): SELECT (SELECT COUNT(*) FROM MyTable1) == (SELECT COUNT(*) FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) AND NOT EXISTS (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) [algorithm: the row counts match, and there are no rows unique to table 1, or table 2] Swift: vIsMatch = (oDict1 == oDict2) UFL: (Map.EqualsRef) [referential equality][do 2 variables point to the same object?][see also: OpEquals/Map.Clone/Any.CopyRef/Any.Address/Map.Equals] AutoHotkey: vIsMatch := (oMap1 == oMap2) C++: vIsMatch = (&oMap1 == &oMap2) C#: vIsMatch = (oDict1 == oDict2) Crystal: vIsMatch = oMap1.same?(oMap2) [also: vIsMatch = (oMap1.object_id == oMap2.object_id)] Excel: ___ Excel VBA: vIsMatch = (ObjPtr(oColl1) = ObjPtr(oColl2)) Go: ___ [can use: vIsMatch := fmt.Sprintf("%p", oMap1) == fmt.Sprintf("%p", oMap2)] Java: vIsMatch = (oMap1 == oMap2) JavaScript: vIsMatch = (oMap1 == oMap2) [also: vIsMatch = (oMap1 === oMap2)] Kotlin: vIsMatch = (oMap1 === oMap2) [note: '===', not '=='] PHP: ___ [can use: $oRefs = [&$oMap1, &$oMap2]; $vIsMatch = ReflectionReference::fromArrayElement($oRefs, 0)->getId() === ReflectionReference::fromArrayElement($oRefs, 1)->getId();] [note: using array as a map] Python: vIsMatch = (oDict1 is oDict2) [inverse: oDict1 is not oDict2] R: ___ [WARNING: 'oVecNew = oVec' creates a copy, not a reference] [note: using a vector as a map] Ruby: vIsMatch = oMap1.equal?(oMap2) Rust: ___ [WARNING: 'oMapNew = oMap' creates a copy, not a reference] Scala: vIsMatch = (oMap1 eq oMap2) [inverse: oMap1 ne oMap2] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [WARNING: 'oMapNew = oMap' creates a copy, not a reference] UFL: Map.Default [define the default value returned when an element with no value is requested][see also: Map.GetOrDefault/Map.ForcePush] AutoHotkey: oMap.Default := vDefault C++: ___ [note: if vKey doesn't exist, 'oMap[vKey]' creates a key with the default value, e.g. 0/""/an empty vector] [note: if vKey doesn't exist, 'oMap[vKey]++' creates a key with the default value, e.g. 0, then increments it] C#: ___ Crystal: ___ [can use (when creating a map): oMap = Hash(String,Int32).new(vDefault)] [can use (modify existing map): if do oMap1.merge!(oMap2), oMap2 will determine the default value] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ [note: '$oMap[$vKey][] = $vValue' creates an array if it doesn't exist, and pushes] [also (increment using default 0): $oMap[$vKey] = ($oMap[$vKey] ?? 0) + 1] Python: ___ [can use (when creating a dict): oDict = defaultdict(oFunc)] [e.g. oDict = defaultdict(lambda: 0)] [e.g. oDict = defaultdict(list)] [requires: from collections import defaultdict] R: ___ Ruby: oMap.default = vDefault [also (when creating a map): oMap = Hash.new(vDefault)] Rust: ___ Scala: ___ [e.g. new map: var oMap = scala.collection.mutable.LinkedHashMap[String,Int]().withDefaultValue(0)] [e.g. new map: var oMap = Map[String,Int]().withDefaultValue(0)] [e.g. modifiable default value: var oMap = Map[String,Int]().withDefault(k=>vDefault)] SQL (MySQL): ___ [can use (create a table with default values): e.g. CREATE TABLE MyTable (k TEXT, v INTEGER DEFAULT 0)] [e.g. CREATE TABLE MyTable (k TEXT, v TEXT DEFAULT '')] SQL (PostgreSQL): ___ [can use (create a table with default values): e.g. CREATE TABLE MyTable (k TEXT, v INTEGER DEFAULT 0)] [e.g. CREATE TABLE MyTable (k TEXT, v TEXT DEFAULT '')] SQL (SQLite): ___ [can use (create a table with default values): e.g. CREATE TABLE MyTable (k TEXT, v INTEGER DEFAULT 0) STRICT] [e.g. CREATE TABLE MyTable (k TEXT, v TEXT DEFAULT '') STRICT] Swift: ___ UFL: (Map.ToObject) [map to object] AutoHotkey: ___ C++: ___ C#: foreach (var oEntry in oDict) ((IDictionary<string,object>)oObj).Add(oEntry) [beforehand: dynamic oObj = new ExpandoObject()] [requires (ExpandoObject): using System.Dynamic] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var oEntry : oMap.entrySet())] [note: oEntry.getKey(), oEntry.getValue()] [see also: 'Object.ToMap'/'Object.Set'] JavaScript: oObj = Object.fromEntries(oMap.entries()) Kotlin: ___ PHP: $oObj = (object)$oMap Python: oObj = SimpleNamespace(**oDict) R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Map.ToString [or Map.ToStr][map to string][see also: String/Map.Print] AutoHotkey: ___ C++: ___ C#: ___ [can use: String.Join("\n", oDict)] [can use: String.Join("\n", oDict.Select(e=>$"{e.Key}:{e.Value}"))] [requires (Select): using System.Linq] Crystal: oMap.to_s Excel: ___ Excel VBA: ___ Go: fmt.Sprintf("%v", oMap) Java: oMap.toString() JavaScript: [...oMap.entries()].join("\n") [WARNING (only prints a type name): String(oMap)] [WARNING (only prints a type name): oMap.toString()] [also: vText = JSON.stringify(Object.fromEntries(oMap.entries()))] Kotlin: oMap.toString() PHP: ___ [can use: var_export($oMap, true)] [also: print_r($oMap, true)] [also (array-like printed as array, map-like printed as object): json_encode($oMap)] Python: str(oDict) R: paste(names(oMap), oMap, sep = ": ", collapse = ", ") [also (returns values only): toString(oMap)] [also: capture.output(print(oMap))] Ruby: oMap.to_s Rust: format!("{:?}", oMap) [also: format!("{:#?}", oMap)] Scala: oMap.toString SQL (MySQL): ___ [can use: SELECT group_concat(concat(k,'=',v) ORDER BY k SEPARATOR '\n') FROM MyTable] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] [also: SELECT group_concat(k||'='||v ORDER BY k SEPARATOR '\n') FROM MyTable] [requires (||): set sql_mode=PIPES_AS_CONCAT] SQL (PostgreSQL): ___ [can use: SELECT string_agg(k||'='||v, E'\n' ORDER BY k) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] SQL (SQLite): ___ [can use: SELECT group_concat(k||'='||v, char(10) ORDER BY k) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] [also: string_agg()] Swift: String(describing:oDict) [also: oDict.description] [also: String(reflecting:oDict)] [also (sorted dict): String(describing:oDict.map{($0,$1)}.sorted(by:{$0.0<$1.0}))] UFL: (Map.ToIni) [map to ini file string] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): SELECT k || '=' || v FROM MyTable [requires (||): set sql_mode=PIPES_AS_CONCAT] [also: SELECT concat(k,'=',v) FROM MyTable] SQL (PostgreSQL): SELECT k || '=' || v FROM MyTable SQL (SQLite): SELECT k || '=' || v FROM MyTable Swift: ___ UFL: Map.CaseSense [set whether key names are case-sensitive/case-insensitive][e.g. case-insensitive: 'ABC'/'Abc'/'abc' would refer to the same key] AutoHotkey: oMap.CaseSense := vMode C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ [note: a related function: array_change_key_case(): 'Changes the case of all keys in an array'] Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ [can use (create a table where key names are unique case-insensitive): CREATE TABLE MyTable (k VARCHAR(20), v TEXT, UNIQUE(k))] [note: for case-sensitive use: VARCHAR(20) BINARY] SQL (PostgreSQL): ___ [can use (create a table where key names are unique case-insensitive): CREATE TABLE MyTable (k TEXT, v TEXT); CREATE UNIQUE INDEX ON MyTable (lower(k));] SQL (SQLite): ___ [can use (create a table where key names (the ASCII chars) are unique case-insensitive): CREATE TABLE MyTable (k TEXT PRIMARY KEY, v TEXT, UNIQUE (k COLLATE NOCASE))] Swift: ___
UFL: Object.Print [or Object.PrintPropValue][print the property-value pairs][see also: PrintKeyValueAsPair/Object.ToString/JsonFromObj] AutoHotkey: ___ C++: ___ C#: Console.WriteLine(String.Join("\n", oObj)) [also: Console.WriteLine(String.Join("\n", (IDictionary<string,object>)oObj))] Crystal: p oObj Excel: ___ Excel VBA: ___ Go: fmt.Println(oObj) [WARNING: prints values but not property names] [also (print prop names/values): fmt.Printf("%+v\n", oObj)] [also (print type and values): fmt.Printf("%T%[1]v\n", oObj)] [also (print type and prop names/values): fmt.Printf("%#v\n", oObj)] Java: for (Field f : oObj.getClass().getFields()) {try {System.out.println(f.getName() + " " + f.get(oObj));} catch (Exception e) {}} [requires: import java.lang.reflect.Field] [e.g. works with int/float/string values] JavaScript: console.log(oObj) [also: console.log(JSON.stringify(oObj, null, 4))] [also: console.log(Object.entries(oObj).join("\n"))] Kotlin: ___ PHP: var_export($oObj) [also: var_dump($oObj)] [also: print_r($oObj)] Python: print(oObj) R: print(oObj) [also: mapply(\(v) slot(oObj,v), slotNames(oObj))] [also: paste(slotNames(oObj), mapply(\(v) slot(oObj,v), slotNames(oObj)), sep = ": ", collapse = ", ")] Ruby: p oObj Rust: println!("{:?}", oObj) [also: println!("{:#?}", oObj)] [note: to print a struct instance via println, you must add '#[derive(Debug)]' above the struct definition] Scala: for (f <- oObj.getClass.getDeclaredFields) {f.setAccessible(true); println((f.getName, f.get(oObj)))} [note: case class: outputs values: println(oObj)] [WARNING: non-case class: outputs type name: println(oObj)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: print(oObj) UFL: Object.LoopPropValue [loop through the items of an object, get property-value pairs one-by-one] AutoHotkey: for vProp, vValue in oObj.OwnProps() C++: ___ C#: foreach (var oEntry in (IDictionary<string,object>)oObj) [note: oEntry.Key, oEntry.Value] [also (for anonymous type): foreach (var oEntry in oObj.GetType().GetProperties())] [note (for anonymous type): oEntry.Name, oEntry.GetValue(oObj)] Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [can use: reflect.ValueOf(oObj)] [MAJOR WARNING: retrieving info may fail if field names don't start with capital letters (upper case)] [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: for (Field oField : oObj.getClass().getFields()) [note: property/value: oField.getName(), oField.get(oObj)] [note: get()/set() must be within a try block] [requires: import java.lang.reflect.Field] JavaScript: for (const [vProp, vValue] of Object.entries(oObj)) [also: for (var vProp in oObj)] [note: cannot use 'of' with Object, since it is not iterable] Kotlin: ___ PHP: foreach ($oObj as $vProp=>$vValue) Python: for vProp, vValue in oObj.__dict__.items(): R: for (vProp in slotNames(oObj)) [note: vValue = slot(oObj, vProp)] Ruby: for vProp, vValue in oObj.each_pair [also: vValue = oObj[:"#{vProp}"]] [also: for vValue in oObj] [afterwards: end] Rust: ___ Scala: for (oField <- oObj.getClass.getDeclaredFields) [note: property/value: oField.getName, oField.get(oObj)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for (vProp, vValue) in Mirror(reflecting:oObj).children UFL: Object.ForEach [or Object.LoopForEach][call a function once for each item of an object][see also: Object.LoopPropValue/Object.ToMap] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: ___ [see also: 'Object.ToMap'] JavaScript: ___ [can use: new Map(Object.entries(oObj)).forEach(oFunc)] [note: Func receives value/key/object] Kotlin: ___ PHP: ___ Python: ___ R: for (p in slotNames(oObj)) {oFunc(p, slot(oObj, p))} Ruby: oObj.each_pair{|p,v| oFunc.call(p,v)} Rust: ___ Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Object.NewEmpty [or Object.NewBasic/Object.EmptyNew][create an empty JavaScript-like object (dot notation e.g. 'vValue = oObj.MyProp', modify/add properties) for storing properties][can modify and add properties, unless stated][see also: Object.OrderType] AutoHotkey: oObj := {} [type: Object] C++: ___ [can use: struct MyStructEmp {}] [afterwards: MyStructEmp oObj] [note: can't add properties] [type: e.g. MyStructEmp (typeid: e.g. Z4mainE11MyStructEmp)] C#: dynamic oObj = new ExpandoObject() [note: can modify/add properties] [also (anonymous type: read-only: can't add/modify properties): e.g. var oObj = new {}] [requires (ExpandoObject): using System.Dynamic] [type: ExpandoObject] [type (anonymous type): e.g. <>f__AnonymousType0`3] Crystal: ___ [e.g. record MyStructEmp] [afterwards: oObj = MyStructEmp.new()] [note: can't add properties] [type: e.g. MyStructEmp] Excel: ___ Excel VBA: ___ Go: ___ [e.g. oObj := struct{}{}] [type: struct {}] Java: ___ [can use: public static class MyClass {}] [afterwards: MyClass oObj = new MyClass()] [note: can't add properties] [type: e.g. MyClass] JavaScript: oObj = {} [type: Object] Kotlin: ___ [can use: data class MyDataClassEmp(var dummy:String="") {}][afterwards: oObj = MyDataClassEmp()] [also (singleton): oSingleton = object {}] [note (both): can't add properties] [type (data class): simple name: e.g. MyDataClassEmp, qualified name: null] [type (singleton): null] PHP: $oObj = new stdClass() [type: object (class: stdClass)] [note: member access: uses '->', not '.'] Python: oObj = SimpleNamespace() [type: SimpleNamespace] [note: oObj.__dict__ returns a dict object] [requires: from types import SimpleNamespace] R: ___ [note: setClass requires at least one slot (so can't create an empty object)] Ruby: ___ [e.g. MyStructEmp = Struct.new("MyStructEmp")] [afterwards: oObj = MyStructEmp.new()] [note: can't add properties] [type: Class (e.g. MyStructEmp.class returns 'Class', MyStructEmp.superclass returns 'Struct')] Rust: ___ [e.g. struct MyStructEmp {}] [afterwards: oObj = MyStructEmp {}] [note: can't add properties] [type: e.g. playground::main::MyStructEmp] Scala: ___ [can use: class MyClass()] [afterwards: var oObj = new MyClass()] [type: e.g. MyClass] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [e.g. struct MyStructEmp {}] [afterwards: oObj = MyStructEmp()] [note: can't add properties] [type: e.g. MyStructEmp] UFL: (Object.NewStrDemo) [or Object.NewStrStrDemo][initialise a JavaScript-like object (or the nearest equivalent) with 3 items][see also: ClassDemoFull/Tuple.NewDemo/Object.FromEntries] AutoHotkey: oObj := {p1:"v1", p2:"v2", p3:"v3"} C++: struct MyStruct {std::string p1="v1"; std::string p2="v2"; std::string p3="v3";} [afterwards: MyStruct oObj] [note: can't add properties] C#: foreach (var oEntry in (new Dictionary<string,object>{{"p1","v1"},{"p2","v2"},{"p3","v3"}})) ((IDictionary<string,object>)oObj).Add(oEntry) [beforehand: dynamic oObj = new ExpandoObject()] [also (anonymous type: read-only: can't add/modify properties): e.g. var oObj = new {p1="v1", p2="v2", p3="v3"}] [requires (ExpandoObject): using System.Dynamic] [requires (Dictionary): using System.Collections.Generic] Crystal: ___ [e.g. record MyStruct, p1 : String, p2 : String, p3 : String] [afterwards: oObj = MyStruct.new("v1", "v2", "v3")] [note: can't add properties] [MAJOR WARNING: Crystal forces property names to start with a lower-case letter] Excel: ___ Excel VBA: ___ Go: ___ [e.g. oObj := struct {p1 string; p2 string; p3 string}{"v1", "v2", "v3"}] Java: public static class MyClass {public String p1="v1", p2="v2", p3="v3";} [afterwards: MyClass oObj = new MyClass()] [note: can't add properties] JavaScript: oObj = {p1:"v1", p2:"v2", p3:"v3"} [also: oObj = Object.fromEntries([["p1","v1"], ["p2","v2"], ["p3","v3"]])] Kotlin: data class MyDataClass(var dummy:String="") {var p1="v1"; var p2="v2"; var p3="v3"} [afterwards: oObj = MyDataClass()] [also (singleton): oSingleton = object {var p1="v1"; var p2="v2"; var p3="v3"}] [e.g. oSingleton.p1] [note (both): can't add properties] PHP: $oObj = (object)["p1"=>"v1", "p2"=>"v2", "p3"=>"v3"] Python: oObj = SimpleNamespace(**{"p1":"v1", "p2":"v2", "p3":"v3"}) [requires: from types import SimpleNamespace] R: ___ [e.g. MyStruct = setClass("MyStruct", slots=c(p1="character", p2="character", p3="character"))] [afterwards: oObj = MyStruct(p1="v1", p2="v2", p3="v3")] [note: setClass creates an S4 class] Ruby: ___ [e.g. MyStruct = Struct.new("MyStruct", "p1", "p2", "p3")] [afterwards: oObj = MyStruct.new("v1", "v2", "v3")] [note: can't add properties] Rust: ___ [e.g. struct MyStruct {p1:String, p2:String, p3:String}] [afterwards: oObj = MyStruct {p1:"v1".to_string(), p2:"v2".to_string(), p3:"v3".to_string()}] [note: can't add properties] Scala: ___ [can use: class MyClass(var p1: String="v1", var p2: String="v2", var p3: String="v3")] [afterwards: var oObj = new MyClass()] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [e.g. struct MyStruct {var p1="v1"; var p2="v2"; var p3="v3"}] [afterwards: oObj = MyStruct()] [note: can't add properties] UFL: (Object.NewStrIntDemo) [initialise a JavaScript-like object (or the nearest equivalent) with 3 items][see also: ClassDemoFull/Tuple.NewDemo] AutoHotkey: oObj := {p1:1, p2:2, p3:3} C++: struct MyStruct {int p1=1; int p2=2; int p3=3;} [afterwards: MyStruct oObj] [note: can't add properties] C#: foreach (var oEntry in (new Dictionary<string,object>{{"p1",1},{"p2",2},{"p3",3}})) ((IDictionary<string,object>)oObj).Add(oEntry) [beforehand: dynamic oObj = new ExpandoObject()] [also (anonymous type: read-only: can't add/modify properties): e.g. var oObj = new {p1=1, p2=2, p3=3}] [requires (ExpandoObject): using System.Dynamic] [requires (Dictionary): using System.Collections.Generic] Crystal: ___ [e.g. record MyStruct, p1 : Int32, p2 : Int32, p3 : Int32] [afterwards: oObj = MyStruct.new(1, 2, 3)] [note: can't add properties] [MAJOR WARNING: Crystal forces property names to start with a lower-case letter] Excel: ___ Excel VBA: ___ Go: ___ [e.g. oObj := struct {p1 int; p2 int; p3 int}{1, 2, 3}] Java: public static class MyClass {public int p1=1, p2=2, p3=3;} [afterwards: MyClass oObj = new MyClass()] [note: can't add properties] JavaScript: oObj = {p1:1, p2:2, p3:3} Kotlin: data class MyDataClass(var dummy:String="") {var p1=1; var p2=2; var p3=3} [afterwards: oObj = MyDataClass()] [also (singleton): oSingleton = object {var p1=1; var p2=2; var p3=3}] [e.g. oSingleton.p1] [note (both): can't add properties] PHP: $oObj = (object)["p1"=>1, "p2"=>2, "p3"=>3] Python: oObj = SimpleNamespace(**{"p1":1, "p2":2, "p3":3}) [requires: from types import SimpleNamespace] R: ___ [e.g. MyStruct = setClass("MyStruct", slots=c(p1="numeric", p2="numeric", p3="numeric"))] [afterwards: oObj = MyStruct(p1=1, p2=2, p3=3)] [note: setClass creates an S4 class] Ruby: ___ [e.g. MyStruct = Struct.new("MyStruct", "p1", "p2", "p3")] [afterwards: oObj = MyStruct.new(1, 2, 3)] [note: can't add properties] Rust: ___ [e.g. struct MyStruct {p1:i32, p2:i32, p3:i32}] [afterwards: oObj = MyStruct {p1:1, p2:2, p3:3}] [note: can't add properties] Scala: ___ [can use: class MyClass(var p1: Int=1, var p2: Int=2, var p3: Int=3)] [afterwards: var oObj = new MyClass()] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [e.g. struct MyStruct {var p1=1; var p2=2; var p3=3}] [afterwards: oObj = MyStruct()] [note: can't add properties] UFL: (Object.OrderType) [insertion order, alphabetical order, 'random' order (unordered)][e.g. what order does a loop return] AutoHotkey: ___ [item order: {}: alphabetical (case *insensitive*) (AHK v1: also case-insensitive)] C++: ___ C#: ___ [item order: ExpandoObject (and anonymous type): insertion] Crystal: ___ [item order: MyStruct: insertion] Excel: ___ Excel VBA: ___ Go: ___ [item order: struct {}: insertion] Java: ___ [item order: MyClass: insertion] JavaScript: ___ [item order: {}: insertion] Kotlin: ___ PHP: ___ [item order: stdClass: insertion] Python: ___ [item order: SimpleNamespace: insertion] R: ___ [item order: MyStruct: insertion] Ruby: ___ [item order: MyStruct: insertion] Rust: ___ Scala: ___ [item order: MyClass: insertion] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [item order: Struct: insertion] UFL: Object.PropNames [or Object.OwnPropNames/Object.Props/Object.OwnProps] AutoHotkey: oProps := [oObj.OwnProps()*] C++: ___ C#: var oProps = ((IDictionary<string,object>)oObj).Keys Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: ___ [see also: 'Object.ToMap'] JavaScript: oProps = Object.keys(oObj) [also: oProps = Object.getOwnPropertyNames(oObj)] [note (both): returns an array, not an iterator (unlike oArray.keys() and oMap.keys())] Kotlin: ___ PHP: $oProps = array_keys(get_object_vars($oObj)) Python: oProps = list(oObj.__dict__) [also: oObj.__dict__.keys()] R: oProps = slotNames(oObj) [also: attributes(oObj)] [also: unclass(oObj)] [also: unlist(oObj)] Ruby: oProps = oObj.members [also: oProps = oObj.to_h.keys] [also: oProps = oObj.each_pair.map{|p,v|p}] Rust: ___ Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oProps = Mirror(reflecting:oObj).children.map{$0.0!} [note: failed with $0] UFL: Object.Values [or Object.OwnValues] AutoHotkey: oValues := [oObj.OwnProps().Bind(&_,)*] C++: ___ C#: var oValues = ((IDictionary<string,object>)oObj).Values Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: ___ [see also: 'Object.ToMap'] JavaScript: oValues = Object.values(oObj) [note: returns an array, not an iterator (unlike oArray.values() and oMap.values())] Kotlin: ___ PHP: $oValues = array_values(get_object_vars($oObj)) Python: oValues = oObj.__dict__.values() R: ___ [can use: oValues = unname(mapply(\(v) slot(oObj,v), slotNames(oObj)))] Ruby: oValues = oObj.to_a [also: oValues = oObj.to_h.values] Rust: ___ Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oValues = Mirror(reflecting:oObj).children.map{$1} UFL: (Object.Entries) [or Object.ToEntries/Object.OwnEntries] AutoHotkey: ___ C++: ___ C#: string[][] oEntries = ((IDictionary<string,object>)oObj).Select(e=>new[]{e.Key,(string)e.Value}).ToArray() Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: ___ [see also: 'Object.ToMap'] JavaScript: oEntries = Object.entries(oObj) [note: returns an array of arrays, not an iterator (unlike oArray.entries() and oMap.entries())] Kotlin: ___ PHP: foreach (get_object_vars($oObj) as $vProp=>$vValue) array_push($oEntries, [$vProp, $vValue]) [beforehand: $oEntries = []] Python: oEntries = oObj.__dict__.items() R: oEntries = Map(c, names(oMap), oMap, USE.NAMES=FALSE) [beforehand: oMap = mapply(\(v) slot(oObj,v), slotNames(oObj))] [note: returns a list] Ruby: oEntries = oObj.each_pair.to_a [also: oEntries = oObj.to_h.to_a] [note (both): returns an array of arrays] Rust: ___ Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oEntries = Mirror(reflecting:oObj).children.map{[$0!,$1]} UFL: Object.OwnPropCount [or Object.PropCount/Object.Count] AutoHotkey: vCount := ObjOwnPropCount(oObj) C++: ___ [can use (e.g. if all members of the same size, e.g. std::string): e.g. 'vCount = sizeof(oObj)/sizeof(std::string)', e.g. 'vCount = sizeof(MyStruct)/sizeof(std::string)'] C#: vCount = ((IDictionary<string,object>)oObj).Count Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: vCount = oObj.getClass().getFields().length JavaScript: vCount = Object.keys(oObj).length [also: Object.getOwnPropertyNames(oObj).length] Kotlin: ___ PHP: $vCount = count(get_object_vars($oObj)) [also: count((array)$oObj)] Python: vCount = len(oObj.__dict__) R: vCount = length(slotNames(oObj)) Ruby: vCount = oObj.length [also: vCount = oObj.size] [also: vCount = oObj.count] Rust: ___ Scala: vCount = oObj.getClass().getDeclaredFields.length SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vCount = Mirror(reflecting:oObj).children.count UFL: Object.Has [or Object.HasOwn/HasOwnProp/HasOwnProperty][does object have property with property name] AutoHotkey: vHasProp := oObj.HasOwnProp(vProp) [deprecated (AHK v1): oObj.HasKey(vKey)] C++: ___ C#: vHasProp = ((IDictionary<string,object>)oObj).ContainsKey(vProp) Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: ___ [see also: 'Object.ToMap'] JavaScript: vHasProp = (vProp in oObj) [also: oObj.hasOwn(vProp)] [also: oObj.hasOwnProperty(vProp)] [note: '(vProp in oObj)' works on all properties, not just own properties] Kotlin: ___ PHP: $vHasProp = property_exists($oObj, $vProp) Python: vHasProp = vProp in oObj.__dict__ [inverse: vProp not in oObj.__dict__] R: vHasProp = .hasSlot(oObj, vProp) Ruby: vHasProp = oObj.members.include?(:"#{vProp}") [e.g. oObj.members.include?(:MyProp)] [alias (include?): member? (e.g. oObj.members.member?)] Rust: ___ Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vHasProp = (Mirror(reflecting:oObj).descendant(vProp) != nil) UFL: (Object.GetDemo) [object get property value (fixed property name)][see also: OpMemberAccess] AutoHotkey: vValue := oObj.MyProp C++: vValue = oObj.MyProp C#: vValue = oObj.MyProp Crystal: vValue = oObj.myProp Excel: ___ Excel VBA: vValue = oObj.MyProp Go: vValue := oObj.MyProp Java: vValue = oObj.MyProp JavaScript: vValue = oObj.MyProp Kotlin: vValue = oObj.MyProp PHP: $vValue = $oObj->MyProp Python: vValue = oObj.MyProp R: vValue = slot(oObj, "MyProp") [also: vValue = oObj@MyProp] [also: vValue = oObj$MyProp] Ruby: vValue = oObj.MyProp Rust: vValue = oObj.MyProp Scala: vValue = oObj.MyProp SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vValue = oObj.MyProp UFL: Object.Get [or Object[Prop]/Object.GetPropValue/Object.GetOwnPropValue][object get property value (dynamic property name)] AutoHotkey: vValue := oObj.%vProp% [WARNING (AHK v2+): if property name is not a string, it is coerced to a string] [WARNING: property names are case-insensitive] C++: ___ [e.g. vValue = oObj.MyProp] C#: vValue = ((IDictionary<string,object>)oObj)[vProp] [note: may want to append '.ToString()'] Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: ___ [see also: 'Object.ToMap'] JavaScript: vValue = oObj[vProp] [WARNING: if property name is not a string/symbol, it is coerced to a string] Kotlin: ___ [e.g. vValue = oObj.MyProp] PHP: $vValue = $oObj->$vProp Python: vValue = oObj.__dict__[vProp] R: vValue = slot(oObj, vProp) [also: vValue = attr(oObj, vProp)] [also: vValue = oObj[, vProp]] [also: vValue = unname(unlist(oObj)[vProp])] Ruby: vValue = oObj[:"#{vProp}"] Rust: ___ [e.g. vValue = oObj.MyProp] Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vValue = Mirror(reflecting:oObj).descendant(vProp)! UFL: Object.GetOrDefault [if property non-existent/null, provide default (deviations from this are noted)] AutoHotkey: ___ C++: ___ C#: vValue = ((IDictionary<string,object>)oObj)[vProp] ?? vDefault [note: may want to append '.ToString()'] [note: doesn't work: ((IDictionary<string,object>)oObj).GetValueOrDefault(vProp, vDefault)] [WARNING: ((IDictionary<string,object>)oObj)[vProp] throws if property doesn't exist] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [see also: 'Object.ToMap'] JavaScript: vValue = oObj[vProp] ?? vDefault [note: returns default if value is null/undefined] Kotlin: ___ PHP: $vValue = $oObj->$vProp ?? $vDefault Python: vValue = oObj.__dict__.get(vProp, vDefault) [WARNING: returns None if value is None] R: ___ Ruby: vValue = oObj.members.include?(:"#{vProp}") ? oObj[:"#{vProp}"] : vDefault Rust: ___ Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vValue = Mirror(reflecting:oObj).descendant(vProp) ?? vDefault [WARNING: returns optional nil if value is optional nil] [note: returns default if key doesn't exist] UFL: (Object.SetDemo) [object set property value (fixed property name)][see also: OpMemberAccess] AutoHotkey: oObj.MyProp := "MyValue" C++: oObj.MyProp = "MyValue" C#: oObj.MyProp = "MyValue" Crystal: oObj = oObj.copy_with(myProp: "MyValue") [e.g. oObj = oObj.copy_with(myProp1: "MyValue1", myProp2: "MyValue2", myProp3: "MyValue3")] Excel: ___ Excel VBA: oObj.MyProp = "MyValue" Go: oObj.MyProp = "MyValue" Java: oObj.MyProp = "MyValue" JavaScript: oObj.MyProp = "MyValue" Kotlin: oObj.MyProp = "MyValue" PHP: $oObj->MyProp = "MyValue" Python: oObj.MyProp = "MyValue" R: slot(oObj, "MyProp") = "MyValue" [also: oObj@MyProp = "MyValue"] [also: oObj$MyProp = "MyValue"] Ruby: oObj.MyProp = "MyValue" Rust: oObj.MyProp = "MyValue" Scala: oObj.MyProp = "MyValue" SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oObj.MyProp = "MyValue" UFL: Object.Set [or Object[Prop]][object set property value (dynamic property name)] AutoHotkey: oObj.%vProp% := vValue [also: oObj.DefineProp(vProp, oDesc)] [e.g. oObj.DefineProp("p1", {Value:"v1"})] [e.g. oObj.MyProp := vValue] [WARNING (AHK v2+): if property name is not a string, it is coerced to a string] [WARNING: property names are case-insensitive] C++: ___ [e.g. oObj.MyProp = vValue] C#: ((IDictionary<string,object>)oObj)[vProp] = vValue [e.g. oObj.MyProp = vValue] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [see also: 'Object.ToMap'] [note: to modify an existing value: oField.set(oObj, vValue)] [e.g. oObj.MyProp = vValue] JavaScript: oObj[vProp] = vValue [e.g. oObj.MyProp = vValue] [WARNING: if property name is not a string/symbol, it is coerced to a string] [also: Object.defineProperty(oObj, vProp, oDesc)] Kotlin: ___ [e.g. oObj.MyProp = vValue] PHP: $oObj->$vProp = $vValue [e.g. $oObj->MyProp = $vValue] Python: oObj.__dict__[vProp] = vValue [e.g. oObj.MyProp = vValue] R: slot(oObj, vProp) = vValue [also: attr(oObj, vProp) = vValue] [also: oObj[, vProp] = vValue] Ruby: oObj[:"#{vProp}"] = vValue [e.g. oObj.MyProp = vValue] Rust: ___ [e.g. oObj.MyProp = vValue] Scala: ___ [see also: 'Object.ToMap'] [note: to modify an existing value: oField.set(oObj, vValue)] [e.g. oObj.MyProp = vValue] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [e.g. oObj.MyProp = vValue] UFL: (Object.ForcePush) [an object of arrays: append an item to an array, create the array if it doesn't exist][workaround: specify 'new array' as the default value][perhaps a better name exists, we're pushing to a key, not to the object itself][see also: Object.Default] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: $oObj->$vProp[] = $vValue [beforehand: $oObj = new stdClass()] [WARNING: '$oObj->$vProp[] = $vValue' creates an array if it doesn't exist, and pushes] Python: ___ R: ___ Ruby: (oObj[:"#{vProp}"] ||= []) << vValue [beforehand: oMap = {}] [WARNING: a||=b equivalent to a?a:a=b not a=a||b] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.Fill) [or Object.SetAll][set all properties to the same value] AutoHotkey: ___ C++: ___ C#: ___ [can use: foreach (var p in ((IDictionary<string,object>)oObj).Keys.ToList()) ((IDictionary<string,object>)oObj)[p] = vValue] [note: using ToList because using the iterator and modifying the dictionary simultaneously throws] [requires (ToList): using System.Linq] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [see also: 'Object.ToMap'] [note: to modify an existing value: oField.set(oObj, vValue)] JavaScript: ___ [can use: for (var p in oObj) oObj[p] = vValue] Kotlin: ___ PHP: ___ [can use: foreach ($oObj as $p=>$v) $oObj->$p = $vValue] Python: ___ [can use: for p,v in oObj.__dict__.items(): oObj.__dict__[p] = vValue] R: ___ [can use: for (p in slotNames(oObj)) slot(oObj, p) = vValue] Ruby: ___ [can use: for p,v in oObj.each_pair; oObj[:"#{p}"] = vValue] [afterwards: end] Rust: ___ Scala: ___ [can use: for (f <- oObj.getClass.getDeclaredFields) {f.setAccessible(true); f.set(oObj, vValue)}] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Object.Swap [swap 2 elements] AutoHotkey: ___ C++: ___ [e.g. std::swap(oObj.MyProp1, oObj.MyProp2)] C#: (((IDictionary<string,object>)oObj)[vProp1], ((IDictionary<string,object>)oObj)[vProp2]) = (((IDictionary<string,object>)oObj)[vProp2], ((IDictionary<string,object>)oObj)[vProp1]) [note: destructuring assignment] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ [can use: oObj.MyProp1, oObj.MyProp2 = oObj.MyProp2, oObj.MyProp1] [note: destructuring assignment] Java: ___ JavaScript: [oObj[vProp1], oObj[vProp2]] = [oObj[vProp2], oObj[vProp1]] [also: e.g. [oObj.MyProp1, oObj.MyProp2] = [oObj.MyProp2, oObj.MyProp1]] [note: destructuring assignment] Kotlin: ___ PHP: [$oObj->$vProp1, $oObj->$vProp2] = [$oObj->$vProp2, $oObj->$vProp1] [note: destructuring assignment] Python: oObj.__dict__[vProp1], oObj.__dict__[vProp2] = oObj.__dict__[vProp2], oObj.__dict__[vProp1] [note: destructuring assignment] R: ___ Ruby: oObj[:"#{vProp1}"], oObj[:"#{vProp2}"] = oObj[:"#{vProp2}"], oObj[:"#{vProp1}"] [note: destructuring assignment] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Object.DeleteProp [or Object.DeleteOwnProp][i.e. reduce the property count by 1][see also: VarDelete] AutoHotkey: oObj.DeleteProp(vProp) C++: ___ C#: ((IDictionary<string,object>)oObj).Remove(vProp) Crystal: ___ [can use (if the type allows nils): oObj.myProp = nil] [e.g. type union: String | Int32 | Nil] [e.g. type union: String?] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [note: to assign null: oObj.MyProp = null] JavaScript: delete oObj[vProp] Kotlin: ___ [note: to assign null: oObj.MyProp = null] PHP: unset($oObj->$vProp) [note: to assign null: $oObj->$vProp = null] Python: del oObj.__dict__[vProp] [also: oObj.__dict__.pop(vProp) and oObj.__dict__.popitem(vProp)] R: ___ Ruby: ___ [note: to assign null: oObj.MyProp = nil] Rust: ___ Scala: ___ [note: to assign null: oObj.MyProp = null] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [note: to assign null: oObj.MyProp = nil] UFL: (Object.DeleteOwnProps) [or Object.Clear/Object.DeleteProps][see also: VarDelete] AutoHotkey: ___ C++: ___ [note: to reset values to the defaults: 'oObj = {}', also: 'oObj = MyStruct()'] C#: ((IDictionary<string,object>)oObj).Clear() Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: oObj.__dict__.clear() R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [note: to reset values to the defaults: oObj = MyStruct()] UFL: (Object.Clone) [or Object.Copy][copy the entire object][typically a shallow copy] AutoHotkey: oObjNew := oObj.Clone() C++: oObjNew = oObj [WARNING: this creates a copy, not a reference] C#: foreach (var oEntry in (IDictionary<string,object>)oObj) ((IDictionary<string,object>)oObjNew).Add(oEntry) [beforehand: dynamic oObjNew = new ExpandoObject()] Crystal: oObjNew = oObj [WARNING: this creates a copy, not a reference] [also (e.g. structs defined via the 'record' macro:) oObj = oObj.clone] Excel: ___ Excel VBA: ___ Go: oObjNew = oObj [WARNING: this creates a copy, not a reference] Java: ___ JavaScript: oObjNew = structuredClone(oObj) [also (with caveats): oObjNew = JSON.parse(JSON.stringify(oObj))] [also (with caveats): oObjNew = Object.assign({}, oObj)] Kotlin: oObjNew = oObj.copy() PHP: $oObjNew = (object)(array)$oObj [also (to deep copy, with caveats): $oObjNew = unserialize(serialize($oObj))] Python: oObjNew = SimpleNamespace(**oObj.__dict__) [also: oObjNew = SimpleNamespace(**vars(oObj))] [also: oObjNew = copy.copy(oObj)] [also: oObjNew = copy.deepcopy(oObj)] [requires: import copy] R: oObjNew = oObj [WARNING: this creates a copy, not a reference] Ruby: oObjNew = oObj.clone Rust: oObjNew = oObj.clone() [note: to clone a struct instance via clone, you must add '#[derive(Copy, Clone)]' above the struct definition (or use impl)] Scala: ___ [can use (if a case class): oObjNew = oObj.copy] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oObjNew = oObj [WARNING: this creates a copy, not a reference] UFL: (Object.FromEntries) [or Entries.ToObject][create an object from an array of entries, each entry is an array containing a property name and a value][e.g. 'oEntries = [["p1","v1"], ["p2","v2"], ["p3","v3"]]'] AutoHotkey: ___ C++: ___ C#: foreach (var oEntry in oEntries) ((IDictionary<string,object>)oObj)[oEntry[0]] = oEntry[1] [beforehand: dynamic oObj = new ExpandoObject()] [requires (ExpandoObject): using System.Dynamic] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var oEntry : oEntries)] [see also: 'Object.ToMap'/'Object.Set'] JavaScript: oObj = Object.fromEntries(oEntries) Kotlin: ___ PHP: array_reduce($oEntries, function($vAccum, $oEntry) use (&$oMap) {$oMap[$oEntry[0]] = $oEntry[1];}) [beforehand: $oMap = []] [afterwards: $oObj = (object)$oMap] Python: oObj = SimpleNamespace(**dict(oEntries)) R: ___ Ruby: ___ Rust: ___ Scala: ___ [see also: 'Object.ToMap'/'Object.Set'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.FromFlatEntries) [create an object from an array of alternating property names/values][e.g. 'oFlatEntries = ["p1","v1", "p2","v2", "p3","v3"]'][see also: Array.Chunk/Object.FromEntries/Map.FromFlatEntries] AutoHotkey: ___ C++: ___ C#: foreach (var oEntry in oFlatEntries.Chunk(2).ToArray()) ((IDictionary<string,object>)oObj)[oEntry[0]] = oEntry[1] [beforehand: dynamic oObj = new ExpandoObject()] [requires (ExpandoObject): using System.Dynamic] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oObj = Object.fromEntries(oMap.entries()) [beforehand: oMap = new Map(Array(oFlatEntries.length/2).fill().map((v,k)=>oFlatEntries.slice(k*2, k*2+2)))] Kotlin: ___ PHP: $oObj = (object)$oMap [beforehand (2): array_reduce(array_chunk($oFlatEntries, 2), function($vAccum, $oEntry) use (&$oMap) {$oMap[$oEntry[0]] = $oEntry[1];})] [beforehand (1): $oMap = []] Python: oObj = SimpleNamespace(**oDict) [beforehand: oDict = dict(itertools.batched(oFlatEntries, 2))] [requires: import itertools] [also: oDict = dict([oFlatEntries[i:i+2] for i in range(0, len(oFlatEntries), 2)])] R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.FromTwoArrays) [or Object.FromPropsValues/Object.FromKeysValues][create an object by combining a property name array and a value array (of equal length)][see also: Array.Zip] AutoHotkey: ___ C++: ___ C#: foreach (var i in Enumerable.Range(0, oProps.Length)) ((IDictionary<string,object>)oObj)[oProps[i]] = oValues[i] [requires (Enumerable): using System.Linq] [WARNING (Enumerable.Range): 2nd param is count, not end] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var vValue : oArray)] [see also: 'Object.ToMap'/'Object.Set'] JavaScript: oObj = Object.fromEntries(oProps.map((v,k)=>[v,oValues[k]])) [note: where v is a property name, and k is an array index] Kotlin: ___ PHP: $oObj = (object)array_combine($oProps, $oValues) Python: oObj = SimpleNamespace(**dict(zip(oProps, oValues))) R: ___ Ruby: ___ Rust: ___ Scala: ___ [see also: 'Object.ToMap'/'Object.Set'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.SetMultOverwriteMap) [object overwrite/combine/merge, overwrite/add values, based on a map] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var oEntry : oMap.entrySet())] [note: oEntry.getKey(), oEntry.getValue()] [see also: 'Object.ToMap'/'Object.Set'] JavaScript: oObj = {...oObj, ...Object.fromEntries(oMap.entries())} [also (from objects): oObj1 = {...oObj1, ...oObj2, ...oObj3}] Kotlin: ___ PHP: $oObj = (object)array_replace((array)$oObj, $oMap) [also: $oObj = (object)array_merge((array)$oObj, $oMap)] [also (from objects): $oObj1 = (object)array_replace((array)$oObj1, (array)$oObj2, (array)$oObj3)] [also (from objects): $oObj1 = (object)array_merge((array)$oObj1, (array)$oObj2, (array)$oObj3)] [note: array_replace treats all key names consistently, array_merge uses special handling for numeric keys] Python: oObj.__dict__.update(oDict) [also (from objects): oObj1.__dict__.update(oObj2.__dict__)] R: ___ [can use: for (k in names(oMap)) {slot(oObj, k) = unname(oMap[k])}] [e.g. oMap = c("p1"="v1NEW", "p2"="v2NEW", "p3"="v3NEW")] Ruby: oMap.each_pair{|k,v| oObj[:"#{k}"]=v} Rust: ___ Scala: ___ [see also: 'Object.ToMap'/'Object.Set'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.SetMultOverwriteEntries) [object overwrite/combine/merge, overwrite/add values, based on entries (key-value pairs)] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oObj = {...oObj, ...Object.fromEntries(oEntries)} Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: oEntries.each{|k,v| oObj[:"#{k}"]=v} [also: oEntries.each{|e| oObj[:"#{e[0]}"]=e[1]}] Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.SetMultSkipExistMap) [or Object.SetMultIfAbsent/Object.SetMultNoOverwrite][object combine, add values, if the property doesn't already exist, based on a map (add only, don't overwrite) (maintain original values)] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: for (var oEntry : oMap.entrySet())] [note: oEntry.getKey(), oEntry.getValue()] [see also: 'Object.ToMap'/'Object.Set'] JavaScript: ___ Kotlin: ___ PHP: $oObj = (object)((array)$oObj + $oMap) [also (from objects): $oObj1 = (object)((array)$oObj1 + (array)$oObj2)] [note: unlike Kotlin, this *doesn't* overwrite keys] Python: ___ [can use: oDictCopy = oObj.__dict__.copy(); oObj.__dict__.update(oDict); oObj.__dict__.update(oDictCopy)] [also (from objects): oDictCopy = oObj1.__dict__.copy(); oObj1.__dict__.update(oObj2.__dict__); oObj1.__dict__.update(oDictCopy)] R: ___ Ruby: ___ Rust: ___ Scala: ___ [see also: 'Object.ToMap'/'Object.Set'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.SetMultSkipExistEntries) [or Object.SetMultIfAbsent/Object.SetMultNoOverwrite][object combine, add values, if the property doesn't already exist, based on entries (key-value pairs) (add only, don't overwrite) (maintain original values)] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: Object.Flip [flip properties/values][assumes no duplicates amongst values][see also: Array.Zip] AutoHotkey: ___ C++: ___ C#: dynamic oObjNew = ((IDictionary<string,object>)oObj).ToDictionary(e=>(string)e.Value, e=>(object)e.Key) Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oObjNew = Object.fromEntries(Object.entries(oObj).map(e=>e.reverse())) [also: oObjNew = Object.fromEntries(Object.entries(oObj).map(([k,v])=>[v,k]))] Kotlin: ___ PHP: $oObjNew = (object)array_flip((array)$oObj) Python: oObjNew = SimpleNamespace(**{v:k for k,v in oObj.__dict__.items()}) R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.MultiFlip) [or Object.FlipMulti][flip properties/values][handles duplicates amongst values][property-value pairs to property-array pairs] AutoHotkey: ___ C++: ___ C#: foreach (var oEntry in ((IDictionary<string,object>)oObj).GroupBy(e=>e.Value).ToDictionary(g=>(string)g.Key, g=>(object)g.Select(e=>e.Key).ToArray())) ((IDictionary<string,object>)oObjNew).Add(oEntry) [beforehand: dynamic oObjNew = new ExpandoObject()] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [see also: 'Object.ToMap'/'Object.Set'] JavaScript: for (const [p,v] of Object.entries(oObj)) (v in oObjNew) ? oObjNew[v].push(p) : oObjNew[v] = [p] [beforehand: oObjNew = {}] Kotlin: ___ PHP: foreach ($oObj as $p=>$v) $oObjNew->$v[] = $p [WARNING: '$oObj->$p[] = $v' creates an array if it doesn't exist, and pushes] [beforehand: $oObjNew = new stdClass()] Python: for k,v in oObj.__dict__.items(): oObjNew.__dict__.setdefault(v, []).append(k) [beforehand: oObjNew = SimpleNamespace()] [also: for k,v in oObj.__dict__.items(): oObjNew.__dict__[v] = oObjNew.__dict__.get(v, []) + [k]] R: ___ Ruby: ___ Rust: ___ Scala: ___ [see also: 'Object.ToMap'/'Object.Set'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.MapValues) [map values: apply a function to each value][see also: Object.Flip] AutoHotkey: ___ C++: ___ C#: dynamic oObjNew = ((IDictionary<string,object>)oObj).ToDictionary(e=>(string)e.Key, e=>(object)oFunc((string)e.Value)) Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: oObjNew = Object.fromEntries(Object.entries(oObj).map(e=>[e[0],oFunc(e[1])])) [also: oObjNew = Object.fromEntries(Object.entries(oObj).map(([k,v])=>[k,oFunc(v)]))] Kotlin: ___ PHP: ___ [can use: foreach ($oObj as $p=>$v) $oObjNew->$p = $oFunc($v)] [beforehand: $oObjNew = new stdClass()] Python: oObjNew = SimpleNamespace(**{k:oFunc(v) for k,v in oObj.__dict__.items()}) [also: oObjNew = SimpleNamespace(**dict((k,oFunc(v)) for k,v in oObj.__dict__.items()))] [also: oObjNew = SimpleNamespace(**dict(zip(oObj.__dict__.keys(), map(oFunc, oObj.__dict__.values()))))] R: for (p in slotNames(oObj)) {slot(oObj, p) = oFunc(p, slot(oObj, p))} Ruby: oObj.each_pair{|p,v| oObj[p]=oFunc.call(v)} Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.PropOf) [return first property that contains value][can be used as Object.HasVal/Object.Any][see also: Array.IndexOf/Array.HasVal/Array.Any/Array.Find] AutoHotkey: ___ C++: ___ C#: vProp = ((IDictionary<string,object>)oObj).FirstOrDefault(e=>(string)e.Value == vNeedle).Key Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [see also: 'Object.ToMap'] JavaScript: ___ [can use: vProp = Object.entries(oObj).find(e=>e[1]==vNeedle)[0]] Kotlin: ___ PHP: $vProp = array_search($vNeedle, (array)$oObj) [WARNING: returns false if no match] Python: vProp = next((k for k,v in oObj.__dict__.items() if v == vNeedle), None) R: vProp = names(oMap)[match(vValue, oMap)] [beforehand: oMap = mapply(\(v) slot(oObj,v), slotNames(oObj))] [note: returns NA if no match] Ruby: vProp = oObj.to_h.key(vNeedle) [note: returns nil if no match] Rust: ___ Scala: ___ [see also: 'Object.ToMap'] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vProp = Dictionary(uniqueKeysWithValues:Mirror(reflecting:oObj).children.map{($0!,$1)}).first(where:{$0.value as! String == vNeedle})?.key [note: returns nil if no match] UFL: (Object.Equals) [do the contents of 2 objects match (at least one level deep) (same property-value pairs)] AutoHotkey: ___ C++: ___ C#: ___ [can use: var vIsMatch = (((IDictionary<string,object>)oObj1).Count == ((IDictionary<string,object>)oObj2).Count) && ((IDictionary<string,object>)oObj1).Keys.All(p=>((IDictionary<string,object>)oObj2).ContainsKey(p) && (((IDictionary<string,object>)oObj1)[p] == ((IDictionary<string,object>)oObj2)[p]))] [requires (All): using System.Linq] Crystal: vIsMatch = (oObj1 == oObj2) Excel: ___ Excel VBA: ___ Go: vIsMatch := reflect.DeepEqual(oObj1, oObj2) [also: vIsMatch := (oObj1 == oObj2)] Java: ___ JavaScript: ___ [can use: vIsMatch = (Object.keys(oObj1).length == Object.keys(oObj2).length) && Object.keys(oObj1).every(p=>(p in oObj2) && (oObj1[p] === oObj2[p]))] [also: vIsMatch = (JSON.stringify(oObj1) == JSON.stringify(oObj2))] Kotlin: vIsMatch = oObj1.equals(oObj2) [also: vIsMatch = (oObj1 == oObj2)] [WARNING: only compares properties declared in the constructor] [note: == compares contents, === compares references] PHP: $vIsMatch = ($oObj1 == $oObj2) [note: == compares contents, === compares references] Python: vIsMatch = (oObj1 == oObj2) R: vIsMatch = identical(oObj1, oObj2) Ruby: vIsMatch = (oObj1 == oObj2) Rust: vIsMatch = (oObj1 == oObj2) [also: vIsMatch = oObj1.eq(&oObj2)] [note: requires: '#[derive(PartialEq)]' above struct definition] Scala: ___ [can use (case class): vIsMatch = (oObj1 == oObj2)] [note: for a case class, == compares values, for a non-case class, == compares references] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.EqualsRef) [referential equality][do 2 variables point to the same object?][see also: OpEquals/Object.Clone/Any.CopyRef/Any.Address/Object.Equals] AutoHotkey: vIsMatch := (oObj1 == oObj2) C++: vIsMatch = (&oObj1 == &oObj2) C#: vIsMatch = (oObj1 == oObj2) Crystal: ___ [WARNING (struct instances): 'oObjNew = oObj' copies (clones) an object] [note: 'Structs inherit from Value'] Excel: ___ Excel VBA: ___ Go: ___ [WARNING (struct instances): 'oObjNew = oObj' copies (clones) an object] Java: vIsMatch = (oObj1 == oObj2) JavaScript: vIsMatch = (oObj1 == oObj2) [also: vIsMatch = (oObj1 === oObj2)] Kotlin: vIsMatch = (oObj1 === oObj2) [note: '===', not '=='] PHP: $vIsMatch = ($oObj1 === $oObj2) [note: == compares contents, === compares references] Python: vIsMatch = (oObj1 is oObj2) [inverse: oObj1 is not oObj2] R: ___ [can use (compare addresses): vIsMatch = (substring(sub(" .*$", "", capture.output(.Internal(inspect(oObj1)))), 2)[1] == substring(sub(" .*$", "", capture.output(.Internal(inspect(oObj2)))), 2)[1])] Ruby: vIsMatch = oObj1.equal?(oObj2) Rust: ___ Scala: vIsMatch = (oObj1 eq oObj2) [inverse: oObj1 ne oObj2] [note: for a case class, == compares values, for a non-case class, == compares references] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [WARNING: 'oObjNew = oObj' creates a copy, not a reference] UFL: (Object.Default) [define the default value returned when an element with no value is requested][see also: Object.GetOrDefault/Object.ForcePush] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.ToMap) [object to map] AutoHotkey: ___ C++: ___ C#: Dictionary<string,string> oDict = ((IDictionary<string,object>)oObj).ToDictionary(e=>e.Key, e=>(string)e.Value) Crystal: ___ [note: information can be parsed from oObj.to_s] Excel: ___ Excel VBA: ___ Go: ___ [note: information can be parsed from fmt.Sprintf("%v", oObj) and fmt.Sprintf("%T", oObj)] Java: ___ [can use: for (Field oField : oObj.getClass().getFields())] [note: property/value: oField.getName(), oField.get(oObj)] [note: get()/set() must be within a try block] [requires: import java.lang.reflect.Field] [note: to add to the map: oMap.put(vProp, vValue)] [beforehand: LinkedHashMap<String,String> oMap = new LinkedHashMap<>()] JavaScript: oMap = new Map(Object.entries(oObj)) Kotlin: ___ PHP: $oMap = (array)$oObj Python: oObj.__dict__.copy() R: oMap = mapply(\(v) slot(oObj,v), slotNames(oObj)) Ruby: oMap = oObj.to_h [also (each property name as a string): oMap = oObj.each_pair.map{|p,v|[p.to_s,v]}.to_h] Rust: ___ Scala: oMap = Map((for (f<-oObj.getClass.getDeclaredFields) yield {f.setAccessible(true); (f.getName, f.get(oObj))}): _*) [can use: for (oField <- oObj.getClass.getDeclaredFields)] [note: property/value: oField.getName, oField.get(oObj)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oDict = Dictionary(uniqueKeysWithValues:Mirror(reflecting:oObj).children.map{($0!,$1)}) UFL: Object.ToString [or Object.ToStr][object to string][see also: String/Object.Print/JsonFromObj] AutoHotkey: ___ C++: ___ C#: ___ [can use: String.Join("\n", oObj)] [can use: String.Join("\n", (IDictionary<string,object>)oObj)] [can use: String.Join("\n", ((IDictionary<string,object>)oObj).Select(e=>$"{e.Key}:{e.Value}"))] [requires (Select): using System.Linq] Crystal: oObj.to_s Excel: ___ Excel VBA: ___ Go: fmt.Sprintf("%v", oObj) [WARNING: returns values but not property names] [note: (returns property names and types): fmt.Sprintf("%T", oObj)] Java: ___ [WARNING (only prints a type name): oObj.toString()] JavaScript: Object.entries(oObj).join("\n") [WARNING (only prints a type name): String(oObj)] [WARNING (only prints a type name): oObj.toString()] [also: JSON.stringify(oObj)] [also: JSON.stringify(oObj, null, 4)] Kotlin: ___ [WARNING (only prints a type name): oObj.toString()] PHP: ___ [can use: var_export($oObj, true)] [also: print_r($oObj, true)] Python: str(oObj) R: ___ [can use: paste(slotNames(oObj), mapply(\(v) slot(oObj,v), slotNames(oObj)), sep = ": ", collapse = ", ")] Ruby: oObj.to_s Rust: format!("{:?}", oObj) [also: format!("{:#?}", oObj)] [note: to output a struct instance via format, you must add '#[derive(Debug)]' above the struct definition] Scala: ___ [note: case class: outputs values: oObj.toString] [WARNING: non-case class: outputs type name: oObj.toString] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: String(describing:oObj) [also: String(reflecting:oObj)] UFL: (Object.ToIni) [object to ini file string] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Object.CaseSense) [set whether property names are case-sensitive/case-insensitive] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___
UFL: Range.Print [print start/end/step (or print the values)][see also: Range.ToArray/Range.Length] AutoHotkey: ___ C++: for (const auto& vValue : oRange) std::cout << vValue << "," C#: Console.WriteLine("[" + String.Join(",", oRange) + "]") Crystal: p oRange Excel: ___ Excel VBA: ___ Go: ___ Java: System.out.println(java.util.Arrays.toString(oRange.toArray())) [WARNING: terminal operation, makes oRange unusable] JavaScript: ___ Kotlin: println(oRange) PHP: var_export($oRange) [also: var_dump($oRange)] [also: print_r($oRange)] [note: range() returns an array] Python: print(oRange) R: print(oRange) Ruby: p oRange Rust: println!("{:?}", oRange) Scala: println(oRange) [also: println(oRange.toList)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: print(oRange) UFL: Range.LoopValue [loop through the items of a range, get values one-by-one] AutoHotkey: ___ C++: for (const auto& vValue : oRange) C#: foreach (var vValue in oRange) Crystal: oRange.each do |vValue| [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: for (var vValue : (Iterable<Integer>)oRange::iterator) [also: oRange.forEach(v->System.out.println(v))] [WARNING (both): the iterations are terminal operations, that make oRange unusable] [requires: import java.util.stream.*] JavaScript: ___ Kotlin: for (vValue in oRange) PHP: foreach ($oRange as $vValue) [note: where $oRange is an array] Python: for vValue in oRange: R: for (vValue in oRange) Ruby: oRange.each do |vValue| [afterwards: end] Rust: for vValue in oRange Scala: for (vValue <- oRange) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for vValue in oRange UFL: Range.LoopValueDemo [e.g. 1 to 3 inclusive] AutoHotkey: ___ C++: for (const auto& vValue : std::views::iota(1, 3+1)) [requires: #include <ranges>] C#: foreach (var vValue in Enumerable.Range(1, 3)) [WARNING (Enumerable.Range): 2nd param is count, not end, e.g. inclusive end: Enumerable.Range(vStart, vEnd-vStart+1)] [requires (Enumerable): using System.Linq] Crystal: (1..3).each do |vValue| [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: for (var vValue : (Iterable<Integer>)IntStream.rangeClosed(1, 3)::iterator) [WARNING: the iterations are terminal operations, that make oRange unusable] [requires: import java.util.stream.*] JavaScript: ___ Kotlin: for (vValue in 1..3) PHP: foreach (range(1, 3) as $vValue) [note: where $oRange is an array] Python: for vValue in range(1, 3+1): R: for (vValue in 1:3) Ruby: (1..3).each do |vValue| [afterwards: end] Rust: for vValue in 1..=3 Scala: for (vValue <- Range.inclusive(1,3)) [also: for (i <- 1 to 3)] SQL (MySQL): ___ [can use: SELECT * FROM json_table(concat('[',repeat('0,', 3-1),'0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp] SQL (PostgreSQL): ___ [can use: SELECT * FROM generate_series(1, 3)] SQL (SQLite): ___ [can use: SELECT * FROM generate_series(1, 3)] Swift: for vValue in 1...3 UFL: (Range.LoopWithIndex) [loop through the items of a range, get key-value pairs one-by-one] AutoHotkey: ___ C++: ___ C#: foreach (var e in oRange.Select((v,k)=>new{k,v})) [also: foreach (var oEntry in oRange.Select((v,k)=>new{MyKey=k,MyValue=v}))] [e.g. e.k, e.v] [e.g. oEntry.MyKey, oEntry.MyValue] [requires (Select): using System.Linq] Crystal: oRange.each_with_index do |vValue,vKey| [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) [beforehand: var oArray = oRange.toArray()] [WARNING (toArray): terminal operation, makes oRange unusable] JavaScript: ___ Kotlin: for ((vKey, vValue) in oRange.withIndex()) PHP: foreach ($oRange as $vKey=>$vValue) [note: where $oRange is an array] Python: for vKey, vValue in enumerate(oRange): R: for (i in 1:length(oRange)) [note: vValue = oRange[i]] Ruby: oRange.each_with_index do |vValue,vKey| [afterwards: end] Rust: for (vKey, vValue) in oRange.clone().into_iter().enumerate() Scala: for ((vValue,vKey) <- oRange.view.zipWithIndex) println((vKey,vValue)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for (vKey, vValue) in oRange.enumerated() UFL: Range.ForEach [or Range.LoopForEach][call a function once for each item of a range][see also: Range.LoopValue/Array.ForEach/ForEachPrintDemo] AutoHotkey: ___ C++: std::for_each(std::begin(oRange), std::end(oRange), oFunc) [note: Func receives value] [requires (for_each): #include <algorithm>] C#: ___ [can use: foreach (var v in oRange) oFunc(v)] Crystal: oRange.each{|v| oFunc.call(v)} [also: oRange.each(&oFunc)] Excel: ___ Excel VBA: ___ Go: ___ Java: oRange.forEach(oFunc) [note: Func receives value] [e.g. oRange.forEach(v->System.out.println(v))] [WARNING: the iterations are terminal operations, that make oRange unusable] JavaScript: ___ [can use (indexes stored as array values): oRange.forEach(oFunc)] [also: oRange.forEach(v=>oFunc(v))] [note: Func receives value/key/object] Kotlin: oRange.forEach(oFunc) [also: oRange.forEach{oFunc(it)}] [note: Func receives value] PHP: ___ [can use: foreach ($oRange as $v) $oFunc($v)] [note: range() generates an array] Python: ___ [can use: for v in oRange: oFunc(v)] R: ___ [can use: for (v in oRange) oFunc(v)] [e.g. 1:10 generates a vector] Ruby: oRange.each{|v| oFunc.call(v)} [also: oRange.each(&oFunc)] Rust: oRange.for_each(|v| oFunc(v)) Scala: oRange.foreach(oFunc) [also: oRange.foreach(oFunc(_))] [also: oRange.foreach(v=>oFunc(v))] [note: Func receives value] SQL (MySQL): ___ [can use: SELECT MyFunc(vTemp) FROM json_table(concat('[',repeat('0,', 3-1),'0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp] SQL (PostgreSQL): ___ [can use: SELECT MyFunc(generate_series) FROM generate_series(1, 3)] SQL (SQLite): ___ [can use: SELECT MyFunc(2) FROM generate_series(1, 3)] Swift: oRange.forEach(oFunc) [also: oRange.forEach{oFunc($0)}] [note: Func receives value] UFL: Range.New [or Range.NewBasic1/Range.NewInc/RangeInc][generate numbers a to b (inclusive end)][a <= x <= b][e.g. 1 to 3 inclusive][note: the 'NewBasic' category is used to have 1 example for each object type][see also: LoopCountIncDemo/Array.New1ToNDemo] AutoHotkey: ___ C++: ___ [can use: auto oRange = std::views::iota(1, 3+1)] [requires: #include <ranges>] [type: 'decltype(ranges::iota_view<int, int>(std::forward<int>(__start), std::forward<int>(__bound)))' (typeid: NSt3__26ranges9iota_viewIiiEE)] [WARNING: doesn't throw if 1st value larger than 2nd value] C#: ___ [can use: var oRange = Enumerable.Range(1, 3)] [type: RangeIterator] [WARNING (Enumerable.Range): 2nd param is count, not end, e.g. inclusive end: Enumerable.Range(vStart, vEnd-vStart+1)] [note (generates a Range, not RangeIterator): 1..(3+1)] [requires (Enumerable): using System.Linq] [WARNING: .. operator: exclusive end] Crystal: oRange = 1..3 [type: Range(Int32, Int32)] [WARNING: doesn't throw if 1st value larger than 2nd value] Excel: ___ Excel VBA: ___ Go: ___ Java: var oRange = IntStream.rangeClosed(1, 3) [WARNING: an IntStream can only be iterated over once, it cannot be reused] [type: Head (full: java.util.stream.IntPipeline$Head)] [also: LongStream.rangeClosed] [requires (IntStream): import java.util.stream.*] [WARNING (IntStream): doesn't throw if 1st value larger than 2nd value] JavaScript: ___ [can use (inclusive end, step 1): oArray = Array(vEnd-vStart+1).fill().map((v,k)=>k+vStart)] [also: oArray = [...Array(vEnd-vStart+1).keys()].map(v=>v+vStart)] [type: Array] [e.g. print 1-3: Array(3).fill().forEach((v,k)=>console.log(k+1))] [e.g. print 1-3: [...Array(3).keys()].forEach(v=>console.log(v+1))] Kotlin: oRange = 1..3 [type: IntRange] [also: downTo (like .. but in reverse order)] [also: 1.rangeTo(3)] [WARNING: doesn't throw if 1st value larger than 2nd value] PHP: $oRange = range(1, 3) [type: array] [WARNING: returns an array, not an object that generates values on-the-fly] [note: assumes step is -1 if 1st value larger than 2nd value] Python: ___ [can use: oRange = range(1, 3+1)] [type: range] [WARNING: doesn't throw if 1st value larger than 2nd value] R: oRange = 1:3 [type: 'integer' (note: a vector)] [also: oRange = seq(1, 3, 1)] [type (seq): double (class: numeric) (note: a vector)] [note: assumes step is -1 if 1st value larger than 2nd value] Ruby: oRange = 1..3 [type: Range] [WARNING: doesn't throw if 1st value larger than 2nd value] Rust: oRange = 1..=3 [type: RangeInclusive] [note: RangeInclusive has start/end, but not len] [WARNING: doesn't throw if 1st value larger than 2nd value] Scala: oRange = Range.inclusive(1, 3) [type: Inclusive (scala.collection.immutable.Range$Inclusive)] [WARNING: doesn't throw if 1st value larger than 2nd value] SQL (MySQL): ___ [can use: SELECT group_concat(vTemp SEPARATOR '\n') FROM json_table(concat('[',repeat('0,', 3-1),'0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp] SQL (PostgreSQL): ___ [can use: generate_series(1, 3)] [e.g. SELECT string_agg(''||vTemp, E'\n') FROM generate_series(1, 3) vTemp] SQL (SQLite): ___ [can use: generate_series(1, 3)] [e.g. SELECT group_concat(value, char(10)) FROM generate_series(1, 3)] [also (JSON5 accepts a trailing comma): SELECT key+1 FROM json_each('['||replace(hex(zeroblob(3)), '00', '0,')||']')] [MAJOR WARNING: 'stop' defaults to 4294967295] Swift: oRange = 1...3 [type: ClosedRange<Int>] [also (inclusive end via 'through'): stride(from:vStart, through:vEnd, by:vStep)] [note: can omit 1 value to create a one-sided range] [note: throws if 1st value larger than 2nd value] UFL: (Range.NewUntil) [or Range.NewBasic2/RangeUntil.New/Range.NewExc/RangeExc][generate numbers a to b (exclusive end)][a <= x < b][e.g. 1 to 4 exclusive end (i.e. 1 to 3 inclusive)] AutoHotkey: ___ C++: auto oRange = std::views::iota(1, 4) [requires: #include <ranges>] [type: 'decltype(ranges::iota_view<int, int>(std::forward<int>(__start), std::forward<int>(__bound)))' (typeid: NSt3__26ranges9iota_viewIiiEE)] C#: ___ [can use: var oRange = Enumerable.Range(1, 4-1)] [type: RangeIterator] [WARNING (Enumerable.Range): 2nd param is count, not end, e.g. exclusive end: Enumerable.Range(vStart, vEnd-vStart)] [note (generates a Range, not RangeIterator): 1..3] [requires (Enumerable): using System.Linq] [WARNING: .. operator: exclusive end] Crystal: oRange = 1...4 [type: Range(Int32, Int32)] Excel: ___ Excel VBA: ___ Go: ___ Java: var oRange = IntStream.range(1, 4) [WARNING: an IntStream can only be iterated over once, it cannot be reused] [type: Head (full: java.util.stream.IntPipeline$Head)] [WARNING: IntStream.range: exclusive end] [also: LongStream.range] JavaScript: ___ [can use (exclusive end, step 1): oArray = Array(vEnd-vStart).fill().map((v,k)=>k+vStart)] [type: Array] Kotlin: oRange = 1..<4 [type: IntRange] [also: 1.rangeUntil(4)] PHP: ___ [can use: $oRange = range(1, 4-1)] [type: array] Python: oRange = range(1, 4) [type: range] [WARNING: range: exclusive end] R: ___ [can use: oRange = 1:(4-1)] [type: 'integer' (note: a vector)] [also: oRange = seq(1, 4-1, 1)] [type (seq): double (class: numeric) (note: a vector)] Ruby: oRange = 1...4 [type: Range] Rust: oRange = 1..4 [type: Range] [note: Range has len, but not start/end] [WARNING: .. operator: exclusive end] Scala: oRange = Range(1, 4) [type: Exclusive (scala.collection.immutable.Range$Exclusive)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oRange = 1..<4 [type: Range<Int>] [also (exclusive end via 'to'): stride(from:vStart, to:vEnd, by:vStep)] [note: can omit 1 value to create a one-sided range] UFL: Range.NewWithStep [inclusive end][note: using 1 to 30 inclusive as an example][see also: Array.FilterGetEveryNth/LoopCountIncDemoFloat] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ [can use: oArray = (1..30).step(2).to_a] [also: (1..30).step(2).each do |vValue|] [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: oRange = Stream.iterate(1, i->i<=30, i->i+2) [WARNING: most actions applied to a range object, consume it, making it unusable] JavaScript: ___ Kotlin: oRange = 1..30 step 2 PHP: $oRange = range(1, 30, 2) Python: ___ [can use: oRange = range(1, 30+1, 2)] R: oRange = seq(1, 30, 2) Ruby: ___ [can use: oArray = (1..30).step(2).to_a] [also: (1..30).step(2).each do |vValue|] [also: (1..30).%(2).each do |vValue|] [afterwards: end] Rust: oRange = (1..=30).step_by(2) Scala: oRange = Range.inclusive(1, 30, 2) SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: generate_series(1, 30, 2)] [e.g. SELECT string_agg(''||vTemp, E'\n') FROM generate_series(1, 30, 2) vTemp] SQL (SQLite): ___ [can use: generate_series(1, 30, 2)] [e.g. SELECT group_concat(value, char(10)) FROM generate_series(1, 30, 2)] Swift: oRange = stride(from:1, through:30, by:2) [e.g. type: StrideThrough<Int>] UFL: (Range.NewUntilWithStep) [exclusive end][note: using 1 to 31 exclusive end (1 to 30 inclusive) as an example][see also: Array.FilterGetEveryNth] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ [can use: oArray = (1...30).step(2).to_a] [also: (1...30).step(2).each do |vValue|] [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: oRange = Stream.iterate(1, i->i<31, i->i+2) [WARNING: most actions applied to a range object, consume it, making it unusable] JavaScript: ___ Kotlin: oRange = 1..<31 step 2 PHP: ___ [can use: $oRange = range(1, 31-1, 2)] Python: oRange = range(1, 31, 2) R: ___ [can use: oRange = seq(1, 31-1, 2)] Ruby: ___ [can use: oArray = (1...30).step(2).to_a] [also: (1...30).step(2).each do |vValue|] [also: (1...30).%(2).each do |vValue|] [afterwards: end] Rust: oRange = (1..31).step_by(2) Scala: oRange = Range(1, 31, 2) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oRange = stride(from:1, to:31, by:2) [e.g. type: StrideTo<Int>] UFL: Range.Length [or Range.Count][algorithm (where / is truediv or truncdiv): count = floor(abs((end-start)/step)) + 1][algorithm (equivalent): count = floor(abs(truediv_or_truncdiv(end-start,step))) + 1][algorithm (alternative): count = abs(truncdiv(end-start,step)) + 1] AutoHotkey: ___ C++: oRange.size() C#: oRange.Count() Crystal: oRange.size Excel: ___ Excel VBA: ___ Go: ___ Java: oRange.count() [also: oRange.summaryStatistics().getCount()] [WARNING (count()/getCount()): terminal operation, makes oRange unusable] JavaScript: ___ Kotlin: oRange.count() PHP: count($oRange) [also: sizeof($oRange)] Python: ___ [can use: vCount = reduce(lambda a,b : a+1, oRange, 0)] [requires: from functools import reduce] R: length(oRange) Ruby: oRange.size [also: oRange.count] Rust: oRange.clone().count() [note: if don't use clone(), the object is consumed] [also (for Range, but not RangeInclusive): oRange.len()] Scala: oRange.length SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: SELECT COUNT(*) FROM generate_series(1, 3)] SQL (SQLite): ___ [can use: SELECT COUNT(*) FROM generate_series(1, 3)] Swift: oRange.count UFL: Range.ToArray [see also: Array.Keys/Array.New1ToNDemo] AutoHotkey: ___ C++: std::iota(oArray, oArray+oRange.size(), oRange.front()) [beforehand: int* oArray = new int[oRange.size()]] [also (array of known size): std::iota(std::begin(oArray), std::end(oArray), oRange.front())] [beforehand (array of known size: replace '123' with the required size): int oArray[123]] [requires (iota): #include <numeric>] [also (vector): std::iota(oVec.begin(), oVec.end(), oRange.front())] [beforehand (vector): std::vector<int> oVec(oRange.size())] C#: oArray = oRange.ToArray() Crystal: oArray = oRange.to_a [also: oArray = oRange.step(vStep).to_a] Excel: ___ Excel VBA: ___ Go: ___ Java: var oArray = oRange.toArray() [WARNING: terminal operation, makes oRange unusable] JavaScript: ___ Kotlin: oArray = oRange.toList().toTypedArray() PHP: $oArray = $oRange [note: the PHP range is an array] Python: oList = list(oRange) R: oVec = oRange [note: the R range is a vector] Ruby: oArray = oRange.to_a [also: oRange.entries] [WARNING: 'entries' objects are typically an array of pairs] [also: oArray = oRange.step(vStep).to_a] Rust: oVec = oRange.collect::<Vec<_>>() [e.g. inclusive end: (vNum1..=vNum2).collect()] Scala: oArray = oRange.toArray [also: oRange.toList] SQL (MySQL): ___ [can use (where column k contains consecutive ints): UPDATE MyTable SET v=k] [e.g. UPDATE MyTable SET v=k*5-5] SQL (PostgreSQL): ___ [can use (where column k contains consecutive ints): UPDATE MyTable SET v=k] [e.g. UPDATE MyTable SET v=k*5-5] SQL (SQLite): ___ [can use (where column k contains consecutive ints): UPDATE MyTable SET v=k] [e.g. UPDATE MyTable SET v=k*5-5] Swift: oArray = Array(oRange) UFL: (Range.Entries) [or Range.ToEntries] AutoHotkey: ___ C++: oEntries.push_back(std::make_pair(i, oRange[i])) [beforehand: std::vector<std::pair<int,int>> oEntries] C#: int[][] oEntries = oRange.Select((v,k)=>new[]{k,v}).ToArray() Crystal: oEntries = oRange.each_with_index.map{|v,k| {k,v}}.to_a [note: can also use: '[k,v]'] Excel: ___ Excel VBA: ___ Go: ___ Java: for (int i=0; i<oArray.length; i++) oEntries[i] = new int[]{i, oArray[i]} [beforehand: int[][] oEntries = new int[oArray.length][2]] [beforehand: oArray = oRange.toArray()] JavaScript: ___ [can use: oEntries = oRange.entries()] [note: where oRange is an array] Kotlin: oEntries = oRange.mapIndexed{k,v->k to v!!}.toMap().entries PHP: foreach ($oRange as $vKey=>$vValue) array_push($oEntries, [$vKey, $vValue]) [beforehand: $oEntries = []] [also: $oEntries = array_map(function($oKey) use ($oRange) {return [$oKey, $oRange[$oKey]];}, array_keys($oRange))] [note: the PHP range is an array] Python: oEntries = {k:v for k,v in enumerate(oRange)}.items() R: oEntries = setNames(oRange, 1:length(oRange)) [also: oEntries = oRange; names(oEntries) = 1:length(oRange)] [note: setNames param order: values then keys] Ruby: oEntries = oRange.map.with_index{|v,k| [k,v]} [also: oEntries = oRange.each_with_index.map{|v,k| [k,v]}] Rust: oEntries = oRange.clone().into_iter().enumerate().collect::<Vec<_>>() Scala: oEntries = oRange.zipWithIndex.toArray SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oEntries = oRange.enumerated().map{[$0,$1]} UFL: Range.Start [get first element] AutoHotkey: ___ C++: oRange.front() C#: oRange.First() Crystal: oRange.min [also: oRange.begin] [also: oRange.first] Excel: ___ Excel VBA: ___ Go: ___ Java: oRange.min().orElseThrow() [note: orElseThrow() to unwrap optional value] [also: oRange.summaryStatistics().getMin()] [WARNING (min()/getMin()): terminal operation, makes oRange unusable] JavaScript: ___ Kotlin: oRange.start PHP: ___ Python: oRange.start R: oRange[1] Ruby: oRange.min [also: oRange.begin] [also: oRange.first] Rust: oRange.start [note: for RangeInclusive, but not Range] Scala: oRange.start [also: oRange.head] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oRange.lowerBound UFL: Range.End [get last element (or exclusive boundary that is never reached)] AutoHotkey: ___ C++: oRange.back() C#: oRange.Last() Crystal: oRange.max [also: oRange.end] [note: max/end can differ, max is the last element] [also: oRange.excludes_end?] [also: oRange.exclusive?] Excel: ___ Excel VBA: ___ Go: ___ Java: oRange.max().orElseThrow() [note: orElseThrow() to unwrap optional value] [also: oRange.summaryStatistics().getMax()] [WARNING (max()/getMax()): terminal operation, makes oRange unusable] JavaScript: ___ Kotlin: oRange.endInclusive [deprecated: oRange.endExclusive] PHP: ___ Python: oRange.stop R: tail(oRange, 1) Ruby: oRange.max [also: oRange.end] [also: oRange.last] [note: max/end/last can differ, max is the last element] [also: oRange.exclude_end?] Rust: oRange.end [note: for RangeInclusive, but not Range] Scala: oRange.end [also: oRange.last] [note: value of last element in range, can differ from inclusive/exclusive range end boundary] SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: SELECT max(generate_series) FROM generate_series(1, 10)] SQL (SQLite): ___ [can use: SELECT max(value) FROM generate_series(1, 10)] Swift: oRange.upperBound UFL: Range.Step [get step (numerical distance between each element)] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: oRange.step R: vStep = oRange[2] - oRange[1] Ruby: ___ Rust: ___ Scala: oRange.step SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ UFL: (Range.Clone) [or Range.Copy] AutoHotkey: ___ C++: auto oRangeNew = oRange [WARNING: this creates a copy, not a reference] C#: var oRangeNew = Enumerable.Range(oRange.First(), oRange.Count()) [WARNING (Enumerable.Range): 2nd param is count, not end] [requires (Enumerable): using System.Linq] Crystal: oRangeNew = oRange.clone Excel: ___ Excel VBA: ___ Go: ___ Java: var oRangeNew = IntStream.rangeClosed(oStats.getMin(), oStats.getMax()) [beforehand (WARNING: terminal operation, makes oRange unusable): var oStats = oRange.summaryStatistics()] [note: works on ranges created by both IntStream.range() and IntStream.rangeClosed()] [note: the statistics object can be used as often as desired, unlike the range object] JavaScript: ___ Kotlin: oRangeNew = oRange.start..oRange.endInclusive [e.g. works with 1..3 and 1..<4, both of type IntRange] PHP: ___ Python: oRangeNew = range(oRange.start, oRange.stop, oRange.step) R: oRangeNew = oRange [WARNING: this creates a copy, not a reference] Ruby: oRangeNew = oRange.clone Rust: oRangeNew = oRange.clone() Scala: ___ [can use (copy reference): oRangeNew = oRange] [also: var oRange = Range.inclusive(oRange.start, oRange.end, oRange.step)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oRangeNew = type(of:oRange).init(uncheckedBounds:(lower:oRange.lowerBound, upper:oRange.upperBound)) [note: confirmed to work with ClosedRange<Int> and Range<Int>] UFL: (Range.Sum) [see also: Sum/Array.Sum/Triang] AutoHotkey: ___ C++: int vSum = std::accumulate(std::begin(oRange), std::end(oRange), 0) [requires (accumulate): #include <numeric>] C#: vSum = oRange.Sum() Crystal: vSum = oRange.sum [also: vSum = oRange.step(vStep).sum] Excel: ___ Excel VBA: ___ Go: ___ Java: var vSum = oRange.sum() [WARNING: terminal operation, makes oRange unusable] JavaScript: ___ [can use: vSum = oArray.reduce((a,v)=>a+v, 0)] [note: negative zero: use seed 0 so that [-0.0].sum() returns 0.0 not -0.0, like most programming languages] Kotlin: vSum = oRange.sum() PHP: $vSum = array_sum($oRange) [note: the PHP range is an array] Python: vSum = sum(oRange) R: vSum = sum(oRange) [note: the R range is a vector] Ruby: vSum = oRange.sum [also: vSum = oRange.step(vStep).sum] Rust: vSum: i32 = oRange.clone().into_iter().sum() [note: clone() can be omitted, but this would make oRange unusable] Scala: vSum = oRange.sum SQL (MySQL): ___ SQL (PostgreSQL): ___ [can use: SELECT SUM(generate_series) FROM generate_series(1, 10)] SQL (SQLite): ___ [can use: SELECT SUM(value) FROM generate_series(1, 10)] Swift: vSum = oRange.reduce(0, +)
UFL: (Tuple.Print) [print the values][see also: Tuple.NewDemo] AutoHotkey: ___ C++: std::apply([](auto&&... oArgs) {((std::cout << oArgs << ", "), ...);}, oTuple) [note: also works with pairs] C#: Console.WriteLine(oTuple) [also: Console.WriteLine(oPair)] Crystal: p oTuple Excel: ___ Excel VBA: ___ Go: ___ Java: System.out.println(oEntry) [note: no equivalent to a tuple of any size] JavaScript: ___ Kotlin: println(oPair) [also: println(oTriple)] [also (2-item entry): println(oEntry)] [note: List, nearest equivalent to a tuple of any size] PHP: ___ Python: print(oTuple) R: ___ Ruby: ___ Rust: println!("{:?}", oTuple) Scala: println(oTuple) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: print(oTuple) UFL: (Tuple.LoopValue) [loop through the items of a tuple, get values one-by-one] AutoHotkey: ___ C++: ___ [note: doable but long-winded] C#: ___ Crystal: oTuple.each do |vValue| [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: for (vValue in oPair.toList()) [also: for (vValue in oTriple.toList())] PHP: ___ Python: for vValue in oTuple: R: ___ Ruby: ___ Rust: ___ Scala: for (vValue <- oTuple.toArray) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for vValue in Mirror(reflecting:oTuple).children.map({$0.value}) [also (shorter, but gives a syntax warning): for vValue in Mirror(reflecting:oTuple).children.map{$0.value}] UFL: (Tuple.LoopWithIndex) [loop through the items of a tuple, get key-value pairs one-by-one] AutoHotkey: ___ C++: ___ [note: doable but long-winded] C#: ___ Crystal: oTuple.each_with_index do |vValue,vKey| [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: for ((vKey, vValue) in oPair.toList().withIndex()) [also: for ((vKey, vValue) in oTriple.toList().withIndex())] PHP: ___ Python: for vKey, vValue in enumerate(oTuple): R: ___ Ruby: ___ Rust: ___ Scala: for ((vValue,vKey) <- oTuple.toArray.zipWithIndex) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for oTuple in Mirror(reflecting:oTuple).children.map({($0.label!,$0.value)}) [also (shorter, but gives a syntax warning): for oTuple in Mirror(reflecting:oTuple).children.map{($0.label!,$0.value)}] [e.g. vKey = oTuple.0] [e.g. vValue = oTuple.1] UFL: (Tuple.NewEmpty) [or Tuple.NewBasic/Tuple.EmptyNew][create an empty tuple][see also: Tuple.NewDemo] AutoHotkey: ___ C++: oTuple = std::make_tuple() [type: tuple<> (typeid: e.g. NSt3__25tupleIJEEE)] C#: ___ [note: ("a", 1) has type ValueTuple`2] [also: Pair] Crystal: oTuple = Tuple.new Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [note: Map.entry("a", 1) has type KeyValueHolder] [note: new AbstractMap.SimpleEntry<>("a", 1) has type SimpleEntry] [note: no equivalent to a tuple of any size] [requires (Map): import java.util.*] JavaScript: ___ Kotlin: ___ [note: Pair("a", 1) has type Pair] [note: mutableMapOf("a" to 1).entries.first() has type Entry] [also: Triple] [note: List, nearest equivalent to a tuple of any size] PHP: ___ Python: oTuple = () [type: tuple] R: ___ Ruby: ___ Rust: oTuple = () [type: '()'] [e.g. ("a", 1) has type '(&str, i32)'] Scala: ___ [can use: oTuple = ()] [type: void] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oTuple = () [type: '()'] [e.g. ("a", 1) has type '(String, Int)'] UFL: (Tuple.NewSize1) [initialise a tuple with 1 item] AutoHotkey: ___ C++: oTuple = std::make_tuple("a") C#: oTuple = new Tuple<string>("a") Crystal: oTuple = {"a"} Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: oTuple = ("a",) R: ___ Ruby: ___ Rust: oTuple = ("a",) Scala: oTuple = Tuple1("a") SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [note: Swift does not have one-tuples] UFL: (Tuple.NewDemo) [or Tuple.NewSize2][initialise a tuple with 2 items] AutoHotkey: ___ [note: vVar := ("a", 1) is equivalent to vVar := 1] [note (AHK v1): vVar := ("a", 1) is equivalent to vVar := "a"] C++: oTuple = std::make_tuple("a", 1) [also: oPair = std::make_pair("a", 1)] [note: auto vVar = ("a", 1) is equivalent to auto vVar = 1] [requires (tuple): #include <tuple>] [requires (pair): #include <utility>] [type (tuple): 'tuple<typename __unwrap_ref_decay<const char (&)[2]>::type, typename __unwrap_ref_decay<int>::type>' (typeid: NSt3__25tupleIJPKciEEE)] [type (pair): 'pair<typename __unwrap_ref_decay<const char (&)[2]>::type, typename __unwrap_ref_decay<int>::type>' (typeid: NSt3__24pairIPKciEE)] C#: (string, int) oTuple = ("a", 1) [also: (string MyName1, int MyName2) oTuple = ("a", 1)] [also: var oTuple = ("a", 1)] [also: var oPair = new KeyValuePair<string,int>("a", 1)] [type (tuple): ValueTuple`2] [type (pair): KeyValuePair`2] [requires (KeyValuePair): using System.Collections.Generic] Crystal: oTuple = {"a", 1} [note: vVar = ("a", 1) is invalid syntax] [type: e.g. Tuple(String, Int32)] Excel: ___ [note: =("a",1) is invalid syntax] Excel VBA: ___ [note: vVar = ("a", 1) is invalid syntax] Go: ___ [note: vVar := ("a", 1) is invalid syntax] Java: oEntry = new AbstractMap.SimpleEntry<>("a", 1) [also (read-only): oEntry = Map.entry("a", 1)] [note: var vVar = ("a", 1) is invalid syntax] [note: no equivalent to a tuple of any size] [type (AbstractMap.SimpleEntry): SimpleEntry] [type (Map.entry): KeyValueHolder] [requires (Map): import java.util.*] JavaScript: ___ [note: vVar = ("a", 1) is equivalent to vVar = 1] Kotlin: oPair = Pair("a", 1) [also: oTriple = Triple("a", 1, 1.1)] [note: no quadruple/quintuple etc] [note: var vVar = ("a", 1) is invalid syntax] [also: oEntry = mutableMapOf("a" to 1).entries.first()] [note: List, nearest equivalent to a tuple of any size] [types: Pair, Triple, Entry] PHP: ___ [note: $vVar = ("a", 1) is invalid syntax] Python: oTuple = ("a", 1) [type: tuple] R: ___ [note: vVar = ("a", 1) is invalid syntax] Ruby: ___ [note: vVar = ("a", 1) is invalid syntax] Rust: oTuple = ("a", 1) [type: e.g. (&str, i32)] Scala: oTuple = ("a", 1) [type: Tuple2] SQL (MySQL): ___ [note: SELECT ('a', 1) is invalid syntax] SQL (PostgreSQL): ___ [note: SELECT ('a', 1) creates a record] SQL (SQLite): ___ [note: SELECT ('a', 1) is invalid syntax] Swift: oTuple = ("a", 1) [also: oTuple = (MyName1:"a", MyName2:1)] [type: e.g. (String, Int)] UFL: (Tuple.Size) [or Tuple.Length/Tuple.Count] AutoHotkey: ___ C++: std::tuple_size<decltype(oTuple)>::value C#: oTuple.GetType().GetGenericArguments().Length Crystal: oTuple.size Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: oPair.toList().size [also: oTriple.toList().size] PHP: ___ Python: len(oTuple) R: ___ Ruby: ___ Rust: ___ Scala: oTuple.size SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: Mirror(reflecting:oTuple).children.count UFL: (Tuple.Get) [or Tuple[Key]][get dynamically, specify an index][note: 0-based unless stated] AutoHotkey: ___ C++: ___ C#: ___ Crystal: oTuple[vIndex] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: oPair.toList()[vIndex] [also: oTriple.toList()[vIndex]] PHP: ___ Python: oTuple[vIndex] R: ___ Ruby: ___ Rust: ___ Scala: oTuple(vIndex) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: Mirror(reflecting:oTuple).children.map{$0.value}[vIndex] UFL: Tuple.GetFirst [or Tuple.First][e.g. oTuple.0] AutoHotkey: ___ C++: get<0>(oTuple) [note: 0/1/2/...] [also: get<0>(oPair)] [also: oPair.first/oPair.second] C#: oTuple.Item1 [note: Item1/Item2/Item3/...] [also: oPair.Key/oPair.Value] Crystal: oTuple[0] [note: 0/1/2/...] Excel: ___ Excel VBA: ___ Go: ___ Java: oEntry.getKey() [note: getKey/getValue] JavaScript: ___ Kotlin: oPair.first [note: first/second] [also: oTriple.first (i.e. first/second/third)] [also: oPair.toList()[0]] [also: oEntry.key/oEntry.value] PHP: ___ Python: oTuple[0] [note: 0/1/2/...] R: ___ Ruby: ___ Rust: oTuple.0 [note: 0/1/2/...] Scala: oTuple(0) [note: 0/1/2/...] [also (1-based): oTuple._1] [note: _1/_2/_3] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oTuple.0 [note: 0/1/2/...] UFL: (Tuple.Set) [or Tuple[Key]][note: with a hardcoded index value] AutoHotkey: ___ C++: std::get<0>(oTuple) = vValue C#: oTuple.Item1 = vValue Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: oEntry.setValue(vValue) [note: can't change key name] JavaScript: ___ Kotlin: oEntry.setValue(vValue) [note: can't change key name] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oTuple.0 = vValue UFL: (Tuple.Clone) [or Tuple.Copy][copy the entire tuple] AutoHotkey: ___ C++: oTupleNew = oTuple [WARNING: this creates a copy, not a reference] C#: oTupleNew = oTuple [also: oPairNew = oPair] [WARNING (both): this creates a copy, not a reference] Crystal: oTupleNew = oTuple.clone Excel: ___ Excel VBA: ___ Go: ___ Java: oEntryNew = new AbstractMap.SimpleEntry<>(oEntry) JavaScript: ___ Kotlin: oPairNew = oPair [WARNING: this creates a copy, not a reference] [also: oTripleNew = oTriple] PHP: ___ Python: oTupleNew = oTuple [WARNING: this creates a copy, not a reference] [also: oTupleNew = oTuple[:]] R: ___ Ruby: ___ Rust: oTupleNew = oTuple [WARNING: this creates a copy, not a reference] Scala: ___ [can use (copy reference): oTupleNew = oTuple] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oTupleNew = oTuple [WARNING: this creates a copy, not a reference] UFL: (Tuple.ToArray) [tuple to array] AutoHotkey: ___ C++: ___ [note: doable but long-winded] ['Hanc marginis exiguitas non caperet.'] C#: ___ Crystal: oArray = oTuple.to_a Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: oArray = oPair.toList().toTypedArray() PHP: ___ Python: oList = list(oTuple) R: ___ Ruby: ___ Rust: ___ [can do (for homogeneous tuples): oArray = <[i32; 2]>::from(oTuple)] Scala: oTuple.toArray SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oArray = Mirror(reflecting:oTuple).children.map{$0.value}
UFL: Optional.New [create an optional object to store either a value or null][see also (may create optionals): Array.IndexOf/Array.Find/Array.Max/Array.Get/Map.Get/Array.First][see also: Null/IsNull/OpNullCoalescing] AutoHotkey: ___ C++: ___ [e.g. std::optional<int> oOpt = vValue] [type: e.g. optional<int> (typeid: e.g. NSt3__28optionalIiEE)] C#: object? oOpt = vValue [also (other types e.g.): int? oOpt = vValue] [type: e.g. int?] [note: a nullable value type] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: oOpt = Optional.ofNullable(vValue) [also (throws if value is null): oOpt = Optional.of(vValue)] [type: Optional] [requires (Optional): import java.util.*] JavaScript: ___ Kotlin: oOpt: Any? = vValue [also (other types e.g.): oOpt: Int? = vValue] [type: e.g. Int?] [note: a nullable object] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: oOpt = Some(vValue) [type: e.g. core::option::Option<i32>] Scala: oOpt = Option(vValue) [type: None$/Some] [also: Some(vValue)] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oOpt: Any? = vValue [also (other types e.g.): oOpt: Int? = vValue] [type: e.g. Optional<Any>] [type: e.g. Optional<Int>] UFL: Optional.NewNull [create an optional object that contains null][see also: Null] AutoHotkey: ___ C++: ___ [e.g. std::optional<int> oOpt = std::nullopt] [type: e.g. optional<int> (typeid: e.g. NSt3__28optionalIiEE)] C#: object? oOpt = null [also (other types e.g.): int? oOpt = null] [type: e.g. int?] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: oOpt = Optional.empty() [type: Optional] [requires (Optional): import java.util.*] JavaScript: ___ Kotlin: oOpt: Any? = null [also (other types e.g.): oOpt: Int? = null] [type: e.g. Int?] [note: a nullable object] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: oOpt = None [type: e.g. core::option::Option<i32>] Scala: oOpt = Option(null) [type: None$] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oOpt: Any? = nil [also (other types e.g.): oOpt: Int? = vValue] [type: e.g. Optional<Any>] [type: e.g. Optional<Int>] UFL: Optional.IsPresent [or Optional.IsNonNull][check if an optional contains a non-null value] AutoHotkey: ___ C++: vIsPresent = oOpt.has_value() C#: vIsPresent = (oOpt != null) [also: oOpt.HasValue] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: vIsPresent = oOpt.isPresent() JavaScript: ___ Kotlin: vIsPresent = (oOpt != null) [also: oOpt !is Nothing?] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: vIsPresent = oOpt.is_some() [also: (oOpt != None)] Scala: vIsPresent = oOpt.isDefined SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vIsPresent = (oOpt != nil) UFL: Optional.IsNull [check if an optional contains null][see also: IsNull] AutoHotkey: ___ C++: vIsNull = !oOpt.has_value() C#: vIsNull = (oOpt == null) [also: !oOpt.HasValue] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: vIsNull = !oOpt.isPresent() JavaScript: ___ Kotlin: vIsNull = (oOpt == null) [also: oOpt is Nothing?] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: vIsNull = oOpt.is_none() [also: (oOpt == None)] Scala: vIsNull = oOpt.isEmpty [also: oOpt.nonEmpty] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vIsNull = (oOpt == nil) UFL: Optional.Unwrap [get a value from an optional (typically throws if the optional contains null)] AutoHotkey: ___ C++: vValue = oOpt.value() C#: ___ [can use: e.g. vValue = (int)oOpt] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: vValue = oOpt.get() [throws if contains null] JavaScript: ___ Kotlin: vValue = oOpt!! [throws if contains null] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: vValue = oOpt.unwrap() [throws if contains None] Scala: vValue = oOpt.get [throws if contains null] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vValue = oOpt! [throws if contains nil] UFL: Optional.UnwrapOrDefault [get a value from an optional, return the default value if the optional contains null][see also: OpNullCoalescing/Array.GetOrDefault] AutoHotkey: ___ C++: vValue = oOpt.value_or(vDefault) C#: vValue = oOpt ?? vDefault [note: unwraps value] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: vValue = oOpt.orElse(vDefault) [also: vValue = oOpt.orElseGet(oFunc)] [note: unwraps value] JavaScript: ___ Kotlin: vValue = oOpt ?: vDefault [WARNING: in Kotlin, '?:' is a null-coalescing operator, not a short-ternary operator: e.g. '0 ?: 123' returns 0, since 0 is non-null] [note: unwraps value] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: vValue = oOpt.unwrap_or(vDefault) Scala: vValue = oOpt.getOrElse(vDefault) [note: unwraps value] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: vValue = oOpt ?? vDefault [note: unwraps value] UFL: Optional.IfLet [if optional object is non-null, unwrap the optional object to the specified variable, and execute the clause] AutoHotkey: ___ C++: ___ C#: ___ [e.g. if (oOpt is int vValue)] [note: if oOpt is non-null, unwraps oOpt to vValue] Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: oOpt?.also [e.g. oOpt?.also {println(it)} ?: run {println("null")}] [e.g. oOpt?.also {v -> println(v)} ?: run {println("null")}] PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: if let Some(vValue) = oOpt [note: if oOpt is non-none, unwraps oOpt to vValue] Scala: ___ [can use: e.g. oOpt.foreach{v => println(v)}] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: if let vValue = oOpt [note: if oOpt is non-nil, unwraps oOpt to vValue]
UFL: Set.Print [print the values][note: for testing set methods, sets a/b/c/d, c/d/e/f, a/b, a/b/c/d/e/f are handy][see also: Set.ToString] AutoHotkey: ___ C++: for (const auto& vValue : oSet) std::cout << vValue << "," C#: Console.WriteLine(String.Join(",", oSet)) Crystal: p oSet Excel: ___ Excel VBA: ___ Go: ___ Java: System.out.println(oSet) JavaScript: console.log(oSet) Kotlin: println(oSet) PHP: ___ Python: print(oSet) R: ___ Ruby: p oSet Rust: println!("{:?}", oSet) [also: println!("{:#?}", oSet)] Scala: println(oSet) SQL (MySQL): SELECT v FROM MyTable SQL (PostgreSQL): SELECT v FROM MyTable SQL (SQLite): SELECT v FROM MyTable Swift: print(oSet) UFL: Set.LoopValue [loop through the items of a set, get values one-by-one] AutoHotkey: ___ C++: for (const auto& vValue : oSet) C#: foreach (var vValue in oSet) Crystal: oSet.each do |vValue| [afterwards: end] Excel: ___ Excel VBA: ___ Go: ___ Java: for (var vValue : oSet) JavaScript: for (const vValue of oSet) Kotlin: for (vValue in oSet) PHP: ___ Python: for vValue in oSet: R: ___ Ruby: for vValue in oSet [afterwards: end] Rust: for vValue in oSet [also: for vValue in &oSet] Scala: for (vValue <- oSet) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: for vValue in oSet UFL: Set.ForEach [or Set.LoopForEach][call a function once for each item of a set][see also: Set.LoopValue] AutoHotkey: ___ C++: std::for_each(std::begin(oSet), std::end(oSet), oFunc) [note: Func receives value] [requires (for_each): #include <algorithm>] C#: ___ [can use: foreach (var v in oSet) oFunc(v)] Crystal: oSet.each{|v| oFunc.call(v)} [also: oSet.each(&oFunc)] Excel: ___ Excel VBA: ___ Go: ___ Java: oSet.forEach(oFunc) [note: Func receives value] JavaScript: oSet.forEach(v=>oFunc(v)) Kotlin: oSet.forEach(oFunc) [also: oSet.forEach{oFunc(it)}] [note: Func receives value] PHP: ___ Python: ___ [can use: for v in oSet: oFunc(v)] R: ___ Ruby: oSet.each{|v| oFunc.call(v)} [also: oSet.each(&oFunc)] Rust: oSet.iter().for_each(|v| oFunc(v)) Scala: oSet.foreach(oFunc) [also: oSet.foreach(oFunc(_))] [also: oSet.foreach(v=>oFunc(v))] [note: Func receives value] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: oSet.forEach(oFunc) [also: oSet.forEach{oFunc($0)}] [note: Func receives value] UFL: Set.NewEmpty [or Set.NewBasic/Set.EmptyNew][create an empty set][workaround: use a map/dictionary][see also: Set.OrderType] AutoHotkey: ___ C++: std::set<std::string> oSet [type: std::set<std::string> (typeid: NSt3__23setINS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEENS_4lessIS6_EENS4_IS6_EEEE)] [requires (set): #include <set>] [requires (unordered_set): #include <unordered_set>] C#: var oSet = new HashSet<string>() [type (note: '1' for all set sizes): HashSet`1] [also (explicit type): HashSet<string> oSet = new HashSet<string>()] [requires (HashSet): using System.Collections.Generic] Crystal: oSet = Set(String).new [type: Set(Int32) / Set(Float64) / Set(String)] [also: oSet = ([] of String).to_set] Excel: ___ Excel VBA: ___ Go: ___ Java: Set<String> oSet = new LinkedHashSet<String>() [type: LinkedHashSet] [requires (LinkedHashSet): import java.util.*] JavaScript: oSet = new Set() [type: Set] Kotlin: oSet: MutableSet<String> = mutableSetOf() [type: LinkedHashSet] PHP: ___ [note: PHP lacks a 'set' object, a workaround: arrays have set-like methods: union via array_merge/array_unique, array_intersect, array_diff] Python: oSet = set() [type: set] R: ___ [note: R lacks a 'set' object, a workaround: vectors have 'set operation' methods: union/intersect/setdiff/setequal] Ruby: oSet = Set[] [type: Set] [requires: require "set"] [also: oSet = [].to_set] Rust: let mut oSet = HashSet::<String>::new() [type: HashSet] [also: let mut oSet: HashSet<String> = HashSet::new()] Scala: oSet = Set() [type (depends on set size): EmptySet$ / Set1 / Set2 / Set3 / Set4 / HashSet] [also: oSet = Set.empty] SQL (MySQL): CREATE TABLE MyTable (v VARCHAR(20) PRIMARY KEY) [type: (table)] SQL (PostgreSQL): CREATE TABLE MyTable (v TEXT PRIMARY KEY) [type: (table)] SQL (SQLite): CREATE TABLE MyTable (v ANY PRIMARY KEY) STRICT [type: (table)] Swift: oSet: Set<String> = [] [also: var oSet = Set<String>()] [type: e.g. Set<Int> / Set<Double> / Set<String> (Int/Double/String sets respectively)] UFL: (Set.NewStrDemo) [initialise a set with 3 items] AutoHotkey: ___ C++: std::set<std::string> oSet({"a", "b", "c"}) [requires (set): #include <set>] [requires (unordered_set): #include <unordered_set>] C#: var oSet = new HashSet<string>{"a", "b", "c"} [also (explicit type): HashSet<string> oSet = new HashSet<string>{"a", "b", "c"}] [requires (HashSet): using System.Collections.Generic] Crystal: oSet = Set{"a", "b", "c"} [also: oSet = ["a", "b", "c"].to_set] Excel: ___ Excel VBA: ___ Go: ___ Java: oSet = new LinkedHashSet<String>(Arrays.asList("a", "b", "c")) [requires (Arrays): import java.util.*] JavaScript: oSet = new Set(["a", "b", "c"]) Kotlin: oSet = mutableSetOf("a", "b", "c") PHP: ___ Python: oSet = {"a", "b", "c"} [also: oSet = set(("a", "b", "c"))] [also: oSet = set(["a", "b", "c"])] [WARNING: set(): a string becomes 1 element per char, e.g. oSet = set("abc")] [MAJOR WARNING: {1, 2, 3} creates a set, not an array] R: ___ Ruby: oSet = Set["a", "b", "c"] [requires: require "set"] [also: oSet = ["a", "b", "c"].to_set] Rust: oSet = HashSet::from(["a", "b", "c"]) [requires: use std::collections::HashSet] Scala: oSet = Set("a", "b", "c") SQL (MySQL): CREATE TABLE MyTable (v VARCHAR(20) PRIMARY KEY); INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c'); SQL (PostgreSQL): CREATE TABLE MyTable (v TEXT PRIMARY KEY); INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c'); SQL (SQLite): CREATE TABLE MyTable (v TEXT PRIMARY KEY) STRICT; INSERT INTO MyTable (v) VALUES ('a'), ('b'), ('c'); Swift: oSet: Set = ["a", "b", "c"] UFL: (Set.NewIntDemo) [initialise a set with 3 items] AutoHotkey: ___ C++: std::set<int> oSet({1, 2, 3}) [requires (set): #include <set>] [requires (unordered_set): #include <unordered_set>] C#: var oSet = new HashSet<int>{1, 2, 3} [also (explicit type): HashSet<int> oSet = new HashSet<int>{1, 2, 3}] [requires (HashSet): using System.Collections.Generic] Crystal: oSet = Set{1, 2, 3} [also: oSet = [1, 2, 3].to_set] Excel: ___ Excel VBA: ___ Go: ___ Java: oSet = new LinkedHashSet<Integer>(Arrays.asList(1, 2, 3)) [requires (Arrays): import java.util.*] JavaScript: oSet = new Set([1, 2, 3]) Kotlin: oSet = mutableSetOf(1, 2, 3) PHP: ___ Python: oSet = {1, 2, 3} [also: oSet = set((1, 2, 3))] [MAJOR WARNING: {1, 2, 3} creates a set, not an array] R: ___ Ruby: oSet = Set[1, 2, 3] [requires: require "set"] [also: oSet = [1, 2, 3].to_set] Rust: oSet = HashSet::from([1, 2, 3]) [requires: use std::collections::HashSet] Scala: oSet = Set(1, 2, 3) SQL (MySQL): CREATE TABLE MyTable (v INTEGER PRIMARY KEY); INSERT INTO MyTable (v) VALUES (1), (2), (3); SQL (PostgreSQL): CREATE TABLE MyTable (v INTEGER PRIMARY KEY); INSERT INTO MyTable (v) VALUES (1), (2), (3); SQL (SQLite): CREATE TABLE MyTable (v INTEGER PRIMARY KEY) STRICT; INSERT INTO MyTable (v) VALUES (1), (2), (3); Swift: oSet: Set = [1, 2, 3] UFL: (Set.OrderType) [insertion order, alphabetical order, 'random' order (unordered)][e.g. what order does a loop return] AutoHotkey: ___ C++: ___ [item order: set: alphabetical (case-sensitive)/numerical] [also: item order: unordered_set: 'random'] C#: ___ [item order: HashSet: insertion] Crystal: ___ [item order: Set: insertion] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [item order: LinkedHashSet: insertion] [item order: HashSet: 'random'] JavaScript: ___ [item order: Set: insertion] Kotlin: ___ [item order: LinkedHashSet: insertion] PHP: ___ Python: ___ [WARNING: item order: set: 'random'] R: ___ Ruby: ___ [item order: Set: insertion] Rust: ___ [item order: BTreeSet: alphabetical (case-sensitive)/numerical] [item order: HashSet: 'random'] Scala: ___ [WARNING: item order: HashSet: 'random'] [also: item order: EmptySet$ / Set1 / Set2 / Set3 / Set4: 'random'] [note: sets with 5 items or more have type HashSet] SQL (MySQL): ___ [item order: (table): insertion] SQL (PostgreSQL): ___ [item order: (table): insertion] SQL (SQLite): ___ [item order: (table): insertion] Swift: ___ [WARNING: item order: Set: 'random'] UFL: Set.Count [or Set.Length][get item count] AutoHotkey: ___ C++: oSet.size() C#: oSet.Count Crystal: oSet.size Excel: ___ Excel VBA: ___ Go: ___ Java: oSet.size() JavaScript: oSet.size Kotlin: oSet.size PHP: ___ Python: len(oSet) R: ___ Ruby: oSet.size [also: oSet.length] [also: oSet.count] Rust: oSet.len() Scala: oSet.size SQL (MySQL): SELECT COUNT(*) FROM MyTable SQL (PostgreSQL): SELECT COUNT(*) FROM MyTable SQL (SQLite): SELECT COUNT(*) FROM MyTable Swift: oSet.count UFL: Set.HasVal [or Set.HasKey][or Set.HasValue/Set.Contains][set contains/includes value (value exists)] AutoHotkey: ___ C++: vHasVal = oSet.contains(vNeedle) [also: vHasVal = oSet.count(vNeedle)] C#: vHasVal = oSet.Contains(vNeedle) Crystal: vHasVal = oSet.includes?(vNeedle) [also: vHasVal = (oSet === vNeedle)] Excel: ___ Excel VBA: ___ Go: ___ Java: vHasVal = oSet.contains(vNeedle) JavaScript: vHasVal = oSet.has(vNeedle) Kotlin: vHasVal = oSet.contains(vNeedle) [also: vHasVal = vNeedle in oSet] [inverse: vNeedle !in oSet] PHP: ___ Python: vHasVal = vNeedle in oSet [inverse: vNeedle not in oSet] R: ___ Ruby: vHasVal = oSet.include?(vNeedle) [also: vHasVal = oSet.member?(vNeedle)] [also: vHasVal = (oSet === vNeedle)] Rust: vHasVal = oSet.contains(vNeedle) Scala: vHasVal = oSet.contains(vNeedle) [WARNING: also (curious syntax): vHasVal = oSet(vNeedle)] SQL (MySQL): SELECT 0 != COUNT(*) FROM MyTable WHERE v=MyValue SQL (PostgreSQL): SELECT 0 != COUNT(*) FROM MyTable WHERE v=MyValue SQL (SQLite): SELECT 0 != COUNT(*) FROM MyTable WHERE v==MyValue Swift: vHasVal = oSet.contains(vNeedle) UFL: Set.Add [add a value][note: often doable via operators][see also: Set.Union] AutoHotkey: ___ C++: oSet.insert(vValue) C#: oSet.Add(vValue) Crystal: oSet.add(vValue) [also: oSet << vValue] Excel: ___ Excel VBA: ___ Go: ___ Java: oSet.add(vValue) JavaScript: oSet.add(vValue) Kotlin: oSet.add(vValue) PHP: ___ Python: oSet.add(vValue) R: ___ Ruby: oSet.add(vValue) [also: oSet << vValue] Rust: oSet.insert(vValue) Scala: oSet = oSet.incl(vValue) [also: oSet += vValue] [also: oSet = oSet + vValue] SQL (MySQL): INSERT INTO MyTable (v) VALUES (MyValue) SQL (PostgreSQL): INSERT INTO MyTable (v) VALUES (MyValue) SQL (SQLite): INSERT INTO MyTable (v) VALUES (MyValue) Swift: oSet.insert(vValue) [also: oSet.update(with:vValue)] [note: insert() adds if not present, update() adds unconditionally] UFL: Set.AddMult [add multiple values][note: often doable via operators][see also: Set.Union] AutoHotkey: ___ C++: ___ [can use: std::for_each(std::begin(oArray), std::end(oArray), [&oSet](std::string v) {oSet.insert(v);})] [also: int vSize = sizeof(oArray)/sizeof(oArray[0]); std::set<std::string>oSetTemp(oArray, oArray+vSize); oSet.merge(oSetTemp)] [WARNING: merge() removes values from one set, and adds them to another] [requires (for_each): #include <algorithm>] C#: oSet.UnionWith(oArray) Crystal: oSet.concat(oArray) [also: oArray.each{|v| oSet.add(v)}] [also: oArray.each(&->oSet.add(String))] Excel: ___ Excel VBA: ___ Go: ___ Java: oSet.addAll(Arrays.asList(oArray)) JavaScript: ___ [can use: oArray.forEach(v=>oSet.add(v))] [also: oSet = new Set([...oSet, ...oArray])] [also: oSetNew = oSet.union(new Set(oArray))] Kotlin: oSet.addAll(oArray) [also: oSet += oArray] [also: oSet = (oSet + oArray).toMutableSet()] PHP: ___ Python: oSet.update(oList) [also: oSet |= oList] [also: oSet = oSet | oList] R: ___ Ruby: oSet.merge(oArray) Rust: oSet.extend(oArray) Scala: oSet = oSet.concat(oArray) [also: oSet ++= oArray] [also: oSet = oSet ++ oArray] SQL (MySQL): ___ [can use: INSERT INTO MyTable (v) VALUES (MyValue1), (MyValue2), (MyValue3)] SQL (PostgreSQL): ___ [can use: INSERT INTO MyTable (v) VALUES (MyValue1), (MyValue2), (MyValue3)] SQL (SQLite): ___ [can use: INSERT INTO MyTable (v) VALUES (MyValue1), (MyValue2), (MyValue3)] Swift: ___ [can use: oSet = oSet.union(oArray)] UFL: Set.Delete [delete a value][note: often doable via operators][see also: Set.Diff/VarDelete] AutoHotkey: ___ C++: ___ [can use: if (oSet.count(vValue)) oSet.erase(oSet.find(vValue))] C#: oSet.Remove(vValue) Crystal: oSet.delete(vValue) Excel: ___ Excel VBA: ___ Go: ___ Java: oSet.remove(vValue) JavaScript: oSet.delete(vValue) Kotlin: oSet.remove(vValue) PHP: ___ Python: oSet.discard(vValue) [also (throws if value not in set): oSet.remove(vValue)] [also: remove random element: oSet.pop()] R: ___ Ruby: oSet.delete(vValue) Rust: oSet.remove(vValue) Scala: oSet = oSet.excl(vValue) [also: oSet -= vValue] [also: oSet = oSet - vValue] SQL (MySQL): DELETE FROM MyTable WHERE v=MyValue SQL (PostgreSQL): DELETE FROM MyTable WHERE v=MyValue SQL (SQLite): DELETE FROM MyTable WHERE v==MyValue Swift: oSet.remove(vValue) UFL: Set.DeleteMult [delete multiple values][note: often doable via operators][see also: Set.Diff] AutoHotkey: ___ C++: ___ [can use: std::for_each(std::begin(oArray), std::end(oArray), [&oSet](std::string v) {if (oSet.count(v)) oSet.erase(oSet.find(v));})] [requires (for_each): #include <algorithm>] C#: oSet.ExceptWith(oArray) Crystal: oSet.subtract(oArray) Excel: ___ Excel VBA: ___ Go: ___ Java: oSet.removeAll(Arrays.asList(oArray)) JavaScript: ___ [can use: oArray.forEach(v=>oSet.delete(v))] [also: oSetNew = oSet.difference(new Set(oArray))] Kotlin: oSet.removeAll(oArray) [also: oSet -= oArray] [also: oSet = (oSet - oArray).toMutableSet()] [also (only keep matching values): oSet.retainAll(oArray)] PHP: ___ Python: oSet.difference_update(oList) [also: oSet -= oList] [also: oSet = oSet - oList] R: ___ Ruby: oSet.subtract(oArray) Rust: ___ [can use: oArray.iter().for_each(|v| {oSet.remove(v);})] Scala: oSet = oSet.removedAll(oArray) [also: oSet --= oArray] [also: oSet = oSet -- oArray] SQL (MySQL): ___ [can use: DELETE FROM MyTable1 WHERE v IN (MyValue1, MyValue2, MyValue3)] [also: DELETE FROM MyTable WHERE v=MyValue] SQL (PostgreSQL): ___ [can use: DELETE FROM MyTable1 WHERE v IN (MyValue1, MyValue2, MyValue3)] [also: DELETE FROM MyTable WHERE v=MyValue] SQL (SQLite): ___ [can use: DELETE FROM MyTable1 WHERE v IN (MyValue1, MyValue2, MyValue3)] [also: DELETE FROM MyTable WHERE v==MyValue] Swift: oSet.subtract(oArray) [can use: oSet = oSet.subtracting(oArray)] UFL: Set.Clear [delete all values][see also: VarDelete] AutoHotkey: ___ C++: oSet.clear() C#: oSet.Clear() Crystal: oSet.clear Excel: ___ Excel VBA: ___ Go: ___ Java: oSet.clear() JavaScript: oSet.clear() Kotlin: oSet.clear() PHP: ___ Python: oSet.clear() R: ___ Ruby: oSet.clear Rust: oSet.clear() Scala: oSetNew = oSet.empty [also: oSetNew = Set()] [also (may not work): oSet.clear()] SQL (MySQL): DELETE FROM MyTable SQL (PostgreSQL): DELETE FROM MyTable SQL (SQLite): DELETE FROM MyTable Swift: oSet.removeAll() UFL: Set.Clone [or Set.Copy][copy the entire set] AutoHotkey: ___ C++: std::set<std::string> oSetNew(oSet) C#: oSetNew = new HashSet<string>(oSet) [also: oSetNew = oSet.MemberwiseClone()] [WARNING (MemberwiseClone): may not work] Crystal: oSetNew = oSet.clone [also: oSetNew = oSet.dup] Excel: ___ Excel VBA: ___ Go: ___ Java: oSetNew = oSet.clone() [also: oSetNew = new LinkedHashSet<String>(oSet)] JavaScript: oSetNew = new Set(oSet) Kotlin: oSetNew = oSet.toMutableSet() [also: oSetNew = oSet.toSet()] PHP: ___ Python: oSetNew = oSet.copy() R: ___ Ruby: oSetNew = oSet.clone [also: oSetNew = oSet.dup] Rust: oSetNew = oSet.clone() Scala: oSetNew = oSet.clone [WARNING (clone): may not work] [also: oSetNew = oSet] [WARNING (=): this creates a copy, not a reference] SQL (MySQL): CREATE TABLE MyTableNew AS SELECT * FROM MyTable SQL (PostgreSQL): CREATE TABLE MyTableNew AS SELECT * FROM MyTable SQL (SQLite): CREATE TABLE MyTableNew AS SELECT * FROM MyTable Swift: oSetNew = oSet [WARNING: this creates a copy, not a reference] UFL: Set.ToString [or Set.ToStr][set to string][see also: String/Set.Print/Set.Join] AutoHotkey: ___ C++: ___ C#: ___ [can use: vText = String.Join(vSep, oSet)] Crystal: vText = oSet.to_s Excel: ___ Excel VBA: ___ Go: ___ Java: vText = oSet.toString() JavaScript: vText = String([...oSet]) [also: vText = [...oSet].toString()] [also: vText = JSON.stringify([...oSet])] Kotlin: vText = oSet.toString() PHP: ___ Python: vText = str(oSet) R: ___ Ruby: vText = oSet.to_s Rust: vText = format!("{:?}", oSet) [also: vText = format!("{:#?}", oSet)] Scala: vText = oSet.toString SQL (MySQL): ___ [can use: SELECT group_concat(v ORDER BY v SEPARATOR MySep) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): ___ [can use: SELECT string_agg(v, MySep ORDER BY v) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] SQL (SQLite): ___ [can use: SELECT group_concat(v, MySep ORDER BY v) FROM MyTable] [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] [also: string_agg()] Swift: vText = String(describing:oSet) [also: vText = oSet.description] [also: vText = String(reflecting:oSet)] UFL: Set.CaseSense [set whether values are case-sensitive/case-insensitive][e.g. case-insensitive: 'ABC'/'Abc'/'abc' would refer to the same value] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ [can use (create a table where values are unique case-insensitive): CREATE TABLE MyTable (v VARCHAR(20), UNIQUE(v))] [note: for case-sensitive use: VARCHAR(20) BINARY] SQL (PostgreSQL): ___ [can use (create a table where values are unique case-insensitive): CREATE TABLE MyTable (v TEXT); CREATE UNIQUE INDEX ON MyTable (lower(v));] SQL (SQLite): ___ [can use (create a table where values (the ASCII chars) are unique case-insensitive): CREATE TABLE MyTable (v TEXT PRIMARY KEY, UNIQUE (v COLLATE NOCASE))] Swift: ___ UFL: Set.Equals [do the contents of 2 sets match (same items, ignore order)][equal if Size(A)=Size(B)=Size(Union(A,B))][equal if Size(A)=Size(B)=Size(Intersection(A,B))][equal if Size(Union(A,B))=Size(Intersection(A,B))][note: often doable via operators][see also: Array.EqualsIgnoreOrder] AutoHotkey: ___ C++: vIsMatch = (oSet1 == oSet2) C#: vIsMatch = oSet1.SetEquals(oSet2) [WARNING: Equals compares references (SetEquals compares contents)] Crystal: vIsMatch = (oSet1 == oSet2) Excel: ___ Excel VBA: ___ Go: ___ Java: vIsMatch = oSet1.equals(oSet2) JavaScript: ___ [can use: vIsMatch = (oSet1.size == oSet2.size) && oSet1.isSubsetOf(oSet2)] Kotlin: vIsMatch = oSet1.equals(oSet2) [also: vIsMatch = (oSet1 == oSet2)] PHP: ___ [can use (arrays) (note: duplicate values can be removed via array_unique): $vIsMatch = (count($oArray1) == count($oArray2)) && (count($oArray1) == (count(array_intersect($oArray1, $oArray2))))] Python: vIsMatch = (oSet1 == oSet2) R: ___ [can use (vectors): vIsMatch = setequal(oVec1, oVec2)] Ruby: vIsMatch = (oSet1 == oSet2) Rust: vIsMatch = (oSet1 == oSet2) [also: vIsMatch = oSet1.eq(&oSet2)] Scala: vIsMatch = oSet1.equals(oSet2) [also: vIsMatch = (oSet1 == oSet2)] SQL (MySQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND 0 = (SELECT COUNT(*) FROM (SELECT v FROM MyTable1 EXCEPT SELECT v FROM MyTable2) oTemp1) AND 0 = (SELECT COUNT(*) FROM (SELECT v FROM MyTable2 EXCEPT SELECT v FROM MyTable1) oTemp2) [algorithm: the row counts match, and there are no items unique to table 1 column, or table 2 column] [MAJOR WARNING: in MySQL, 'EXISTS' must be part of 'WHERE (NOT) EXISTS', unlike PostgreSQL/SQLite] [version: MySQL 8.0.31: EXCEPT added] SQL (PostgreSQL): SELECT (SELECT COUNT(*) FROM MyTable1) = (SELECT COUNT(*) FROM MyTable2) AND NOT EXISTS (SELECT v FROM MyTable1 EXCEPT SELECT v FROM MyTable2) AND NOT EXISTS (SELECT v FROM MyTable2 EXCEPT SELECT v FROM MyTable1) [algorithm: the row counts match, and there are no items unique to table 1 column, or table 2 column] SQL (SQLite): SELECT (SELECT COUNT(*) FROM MyTable1) == (SELECT COUNT(*) FROM MyTable2) AND NOT EXISTS (SELECT v FROM MyTable1 EXCEPT SELECT v FROM MyTable2) AND NOT EXISTS (SELECT v FROM MyTable2 EXCEPT SELECT v FROM MyTable1) [algorithm: the row counts match, and there are no items unique to table 1 column, or table 2 column] Swift: vIsMatch = (oSet1 == oSet2) UFL: (Set.EqualsRef) [referential equality][do 2 variables point to the same object?][see also: OpEquals/Set.Clone/Any.CopyRef/Any.Address/Set.Equals] AutoHotkey: ___ C++: vIsMatch = (&oSet1 == &oSet2) C#: vIsMatch = (oSet1 == oSet2) Crystal: vIsMatch = oSet1.same?(oSet2) [also: vIsMatch = (oSet1.object_id == oSet2.object_id)] Excel: ___ Excel VBA: ___ Go: ___ Java: vIsMatch = (oSet1 == oSet2) JavaScript: vIsMatch = (oSet1 == oSet2) [also: vIsMatch = (oSet1 === oSet2)] Kotlin: vIsMatch = (oSet1 === oSet2) [note: '===', not '=='] PHP: ___ Python: vIsMatch = (oSet1 is oSet2) [inverse: oSet1 is not oSet2] R: ___ Ruby: vIsMatch = oSet1.equal?(oSet2) Rust: ___ [WARNING: 'oSetNew = oSet' creates a copy, not a reference] Scala: vIsMatch = (oSet1 eq oSet2) [inverse: oSet1 ne oSet2] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: ___ [WARNING: 'oSetNew = oSet' creates a copy, not a reference] UFL: Set.Diff [or Set.Difference][return values unique to set 1][start with set 1 elements, remove set 2 elements][note: often doable via operators][see also: Set.DeleteMult] AutoHotkey: ___ C++: ___ [can use: std::vector<std::string> oVecTemp; std::set_difference(oSet1.begin(), oSet1.end(), oSet2.begin(), oSet2.end(), std::inserter(oVecTemp, oVecTemp.begin())); std::set<std::string>oSetNew(oVecTemp.begin(), oVecTemp.end())] [requires (set_difference): #include <algorithm>] C#: oSetNew = Enumerable.Except(oSet1, oSet2).ToHashSet() [can use: var oSetNew = new HashSet<string>(oSet1); oSetNew.ExceptWith(oSet2)] [requires (Enumerable): using System.Linq] Crystal: oSetNew = oSet1 - oSet2 [also: oSet1 -= oSet2] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: var oSetNew = new LinkedHashSet<String>(oSet1); oSetNew.removeAll(oSet2)] JavaScript: oSetNew = oSet1.difference(oSet2) [also: oSetNew = new Set(Array.from(oSet1).filter(v => !oSet2.has(v)))] Kotlin: oSetNew = oSet1.subtract(oSet2) [also: oSetNew = oSet1 subtract oSet2] [also: oSetNew = (oSet1 - oSet2).toMutableSet()] [also: oSet1 -= oSet2] PHP: ___ [can use (arrays): $oArrayNew = array_values(array_diff($oArray1, $oArray2))] [WARNING: array_diff() maintains indexes, use array_values() to reindex an array] Python: oSetNew = oSet1.difference(oSet2) [also: oSetNew = oSet1 - oSet2] [also: oSet1 -= oSet2] [also: oSet1.difference_update(oSet2)] R: ___ [can use (vectors): oVecNew = setdiff(oVec1, oVec2)] Ruby: oSetNew = oSet1.difference(oSet2) [also: oSetNew = oSet1 - oSet2] [also: oSet1 -= oSet2] Rust: oSetNew = HashSet::from_iter(oSet1.difference(&oSet2)) [also: oSetNew = &oSet1 - &oSet2] Scala: oSetNew = oSet1.diff(oSet2) [also: oSetNew = oSet1 &~ oSet2] [also: oSetNew = oSet1 -- oSet2] SQL (MySQL): SELECT * FROM MyTable1 t1 LEFT JOIN MyTable2 t2 ON t1.v = t2.v WHERE t2.v IS NULL [also: SELECT * FROM MyTable1 t1 WHERE NOT EXISTS (SELECT 1 FROM MyTable2 t2 WHERE t1.v = t2.v)] [also: SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2] [version: MySQL 8.0.31: EXCEPT added] SQL (PostgreSQL): SELECT * FROM MyTable1 t1 LEFT JOIN MyTable2 t2 ON t1.v = t2.v WHERE t2.v IS NULL [also: SELECT * FROM MyTable1 t1 WHERE NOT EXISTS (SELECT 1 FROM MyTable2 t2 WHERE t1.v = t2.v)] [also: SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2] SQL (SQLite): SELECT * FROM MyTable1 t1 LEFT JOIN MyTable2 t2 ON t1.v == t2.v WHERE t2.v IS NULL [also: SELECT * FROM MyTable1 t1 WHERE NOT EXISTS (SELECT 1 FROM MyTable2 t2 WHERE t1.v == t2.v)] [also: SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2] Swift: oSetNew = oSet1.subtracting(oSet2) [also: oSet1.subtract(oSet2)] UFL: (Set.SymDiff) [or Set.SymmetricDifference][start with union of set 1 and set 2, remove the intersection][return union of: values unique to set 1, and values unique to set 2][note: often doable via operators] AutoHotkey: ___ C++: ___ [can use: std::vector<std::string> oVecTemp; std::set_symmetric_difference(oSet1.begin(), oSet1.end(), oSet2.begin(), oSet2.end(), std::inserter(oVecTemp, oVecTemp.begin())); std::set<std::string>oSetNew(oVecTemp.begin(), oVecTemp.end())] [requires (set_symmetric_difference): #include <algorithm>] C#: ___ [can use: var oSetNew = new HashSet<string>(oSet1); oSetNew.SymmetricExceptWith(oSet2)] Crystal: oSetNew = oSet1 ^ oSet2 [also: oSet1 ^= oSet2] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: var oSetNew = new LinkedHashSet<String>(oSet1); oSetNew.addAll(oSet2); var oSetTemp = new LinkedHashSet<String>(oSet1); oSetTemp.retainAll(oSet2); oSetNew.removeAll(oSetTemp)] JavaScript: oSetNew = oSet1.symmetricDifference(oSet2) [also: oSetNew = new Set([...oSet1, ...oSet2].filter(v => !oSet1.has(v) || !oSet2.has(v)))] [also: oSetNew = new Set([...Array.from(oSet1).filter(v => !oSet2.has(v)), ...Array.from(oSet2).filter(v => !oSet1.has(v))])] Kotlin: oSetNew = (oSet1-oSet2).union(oSet2-oSet1) [also: oSetNew = (oSet1-oSet2) union (oSet2-oSet1)] PHP: ___ [can use (arrays): $oArrayNew = array_values(array_unique(array_diff(array_merge($oArray1, $oArray2), array_intersect($oArray1, $oArray2))))] [also (arrays): $oArrayNew = array_values(array_unique(array_merge(array_diff($oArray1, $oArray2), array_diff($oArray2, $oArray1))))] [WARNING: array_unique()/array_diff()/array_intersect() maintain indexes, use array_values() to reindex an array] Python: oSetNew = oSet1.symmetric_difference(oSet2) [also: oSetNew = oSet1 ^ oSet2] [also: oSet1 ^= oSet2] [also: oSet1.symmetric_difference_update(oSet2)] R: ___ [can use (vectors): oVecNew = setdiff(union(oVec1, oVec2), intersect(oVec1, oVec2))] [also (vectors): oVecNew = union(setdiff(oVec1, oVec2), setdiff(oVec2, oVec1))] Ruby: oSetNew = oSet1 ^ oSet2 [also: oSet1 ^= oSet2] Rust: oSetNew = HashSet::from_iter(oSet1.symmetric_difference(&oSet2)) [also: oSetNew = &oSet1 ^ &oSet2] Scala: oSetNew = (oSet1--oSet2).union(oSet2--oSet1) [also: oSetNew = (oSet1--oSet2) union (oSet2--oSet1)] SQL (MySQL): SELECT t1.v,t2.v FROM MyTable1 t1 LEFT JOIN MyTable2 t2 ON t1.v = t2.v WHERE t2.v IS NULL UNION ALL SELECT t1.v,t2.v FROM MyTable1 t1 RIGHT JOIN MyTable2 t2 ON t1.v = t2.v WHERE t1.v IS NULL [algorithm: FULL OUTER JOIN not available, workaround: (table 1 diff table 2) union (table 2 diff table 1)] SQL (PostgreSQL): SELECT * FROM MyTable1 t1 FULL OUTER JOIN MyTable2 t2 ON t1.v = t2.v WHERE t1.v IS NULL or t2.v IS NULL SQL (SQLite): SELECT * FROM MyTable1 t1 FULL OUTER JOIN MyTable2 t2 ON t1.v == t2.v WHERE t1.v IS NULL or t2.v IS NULL Swift: oSetNew = oSet1.symmetricDifference(oSet2) [also: oSet1.formSymmetricDifference(oSet2)] UFL: Set.Intersection [return values present in both set 1 and set 2][note: equivalent to Diff(A,Diff(B,A))][note: often doable via operators] AutoHotkey: ___ C++: ___ [can use: std::vector<std::string> oVecTemp; std::set_intersection(oSet1.begin(), oSet1.end(), oSet2.begin(), oSet2.end(), std::inserter(oVecTemp, oVecTemp.begin())); std::set<std::string>oSetNew(oVecTemp.begin(), oVecTemp.end())] [requires (set_intersection): #include <algorithm>] C#: oSetNew = Enumerable.Intersect(oSet1, oSet2).ToHashSet() [can use: var oSetNew = new HashSet<string>(oSet1); oSetNew.IntersectWith(oSet2)] [requires (Enumerable): using System.Linq] Crystal: oSetNew = oSet1 & oSet2 [also: oSet1 &= oSet2] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: var oSetNew = new LinkedHashSet<String>(oSet1); oSetNew.retainAll(oSet2)] JavaScript: oSetNew = oSet1.intersection(oSet2) [also: oSetNew = new Set(Array.from(oSet1).filter(v => oSet2.has(v)))] [also: oSet1.retainAll(oSet2)] Kotlin: oSetNew = oSet1.intersect(oSet2) [also: oSetNew = oSet1 intersect oSet2] PHP: ___ [can use (arrays): $oArrayNew = array_values(array_intersect($oArray1, $oArray2))] [WARNING: array_intersect() maintains indexes, use array_values() to reindex an array] Python: oSetNew = oSet1.intersection(oSet2) [also: oSetNew = oSet1 & oSet2] [also: oSet1 &= oSet2] [also: oSet1.intersection_update(oSet2)] R: ___ [can use (vectors): oVecNew = intersect(oVec1, oVec2)] Ruby: oSetNew = oSet1.intersection(oSet2) [also: oSetNew = oSet1 & oSet2] [also: oSet1 &= oSet2] Rust: oSetNew = HashSet::from_iter(oSet1.intersection(&oSet2)) [also: oSetNew = &oSet1 & &oSet2] Scala: oSetNew = oSet1.intersect(oSet2) [also: oSetNew = oSet1 intersect oSet2] [also: oSetNew = oSet1 & oSet2] SQL (MySQL): SELECT * FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.v = t2.v [also: SELECT * FROM MyTable1 t1 WHERE EXISTS (SELECT 1 FROM MyTable2 t2 WHERE t1.v = t2.v)] SQL (PostgreSQL): SELECT * FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.v = t2.v [also: SELECT * FROM MyTable1 t1 WHERE EXISTS (SELECT 1 FROM MyTable2 t2 WHERE t1.v = t2.v)] SQL (SQLite): SELECT * FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.v == t2.v [also: SELECT * FROM MyTable1 t1 WHERE EXISTS (SELECT 1 FROM MyTable2 t2 WHERE t1.v == t2.v)] Swift: oSetNew = oSet1.intersection(oSet2) [also: oSet1.formIntersection(oSet2)] UFL: Set.Union [create a set with the elements of sets 1 and 2][note: often doable via operators][see also: Set.AddMult] AutoHotkey: ___ C++: ___ [can use: std::vector<std::string> oVecTemp; std::set_union(oSet1.begin(), oSet1.end(), oSet2.begin(), oSet2.end(), std::inserter(oVecTemp, oVecTemp.begin())); std::set<std::string>oSetNew(oVecTemp.begin(), oVecTemp.end())] [requires (set_union): #include <algorithm>] C#: oSetNew = Enumerable.Union(oSet1, oSet2).ToHashSet() [can use: var oSetNew = new HashSet<string>(oSet1); oSetNew.UnionExceptWith(oSet2)] [requires (Enumerable): using System.Linq] Crystal: oSetNew = oSet1 | oSet2 [also: oSetNew = oSet1 + oSet2] [also: oSet1 |= oSet2] [also: oSet1 += oSet2] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ [can use: var oSetNew = new LinkedHashSet<String>(oSet1); oSetNew.addAll(oSet2)] JavaScript: oSetNew = oSet1.union(oSet2) [also: oSetNew = new Set([...oSet1, ...oSet2])] Kotlin: oSetNew = oSet1.union(oSet2) [also: oSetNew = oSet1 union oSet2] [also: oSetNew = (oSet1 + oSet2).toMutableSet()] [also: oSet1 += oSet2] PHP: ___ [can use (arrays): $oArrayNew = array_values(array_unique(array_merge($oArray1, $oArray2)))] [WARNING: array_unique() maintains indexes, use array_values() to reindex an array] Python: oSetNew = oSet1.union(oSet2) [also: oSetNew = oSet1 | oSet2] [also: oSet1 |= oSet2] [also: oSet1.update(oSet2)] R: ___ [can use (vectors): oVecNew = union(oVec1, oVec2)] Ruby: oSetNew = oSet1.union(oSet2) [also: oSetNew = oSet1 | oSet2] [also: oSetNew = oSet1 + oSet2] [also: oSet1 |= oSet2] [also: oSet1 += oSet2] Rust: oSetNew = HashSet::from_iter(oSet1.union(&oSet2)) [also: oSetNew = &oSet1 | &oSet2] Scala: oSetNew = oSet1.union(oSet2) [also: oSetNew = oSet1 | oSet2] [also: oSetNew = oSet1 ++ oSet2] SQL (MySQL): SELECT * FROM MyTable1 t1 FULL OUTER JOIN MyTable2 t2 ON t1.v = t2.v [algorithm: FULL OUTER JOIN not available, workaround: table 1 union (table 2 diff table 1)] SQL (PostgreSQL): SELECT * FROM MyTable1 t1 FULL OUTER JOIN MyTable2 t2 ON t1.v = t2.v SQL (SQLite): SELECT * FROM MyTable1 t1 FULL OUTER JOIN MyTable2 t2 ON t1.v == t2.v Swift: oSetNew = oSet1.union(oSet2) [also: oSet1.formUnion(oSet2)] UFL: Set.IsSubsetOf [is set 1 a subset of set 2][if Diff(A,B) = null set, then A is a subset of B][if A = B, then A is a subset of B (but not a proper subset of B)][note: often doable via operators] AutoHotkey: ___ C++: vIsSubset = std::includes(oSet2.begin(), oSet2.end(), oSet1.begin(), oSet1.end()) [requires (includes): #include <algorithm>] C#: vIsSubset = oSet1.IsSubsetOf(oSet2) [also: vIsProperSubset = oSet1.IsProperSubsetOf(oSet2)] Crystal: vIsSubset = oSet1.subset_of?(oSet2) [also: vIsProperSubset = oSet1.proper_subset_of?(oSet2)] Excel: ___ Excel VBA: ___ Go: ___ Java: vIsSubset = oSet2.containsAll(oSet1) JavaScript: vIsSubset = oSet1.isSubsetOf(oSet2) [also: vIsSubset = Array.from(oSet1).every(v => oSet2.has(v))] Kotlin: vIsSubset = oSet2.containsAll(oSet1) PHP: ___ [can use (arrays): $vIsSubset = !count(array_diff($oArray1, $oArray2))] Python: vIsSubset = oSet1.issubset(oSet2) [also: vIsSubset = (oSet1 <= oSet2)] [also: vIsProperSubset = (oSet1 < oSet2)] R: ___ [can use (vectors): vIsSubset = !length(setdiff(oVec1, oVec2))] Ruby: vIsSubset = oSet1.subset?(oSet2) [also: vIsSubset = (oSet1 <= oSet2)] [also: vIsProperSubset = oSet1.proper_subset?(oSet2)] [also: vIsProperSubset = (oSet1 < oSet2)] Rust: vIsSubset = oSet1.is_subset(&oSet2) Scala: vIsSubset = oSet1.subsetOf(oSet2) SQL (MySQL): SELECT 0 = COUNT(*) FROM (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) oTemp [MAJOR WARNING: in MySQL, 'EXISTS' must be part of 'WHERE (NOT) EXISTS', unlike PostgreSQL/SQLite] [version: MySQL 8.0.31: EXCEPT added] SQL (PostgreSQL): SELECT NOT EXISTS (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) SQL (SQLite): SELECT NOT EXISTS (SELECT * FROM MyTable1 EXCEPT SELECT * FROM MyTable2) Swift: vIsSubset = oSet1.isSubset(of:oSet2) [also: vIsProperSubset = oSet1.isStrictSubset(of:oSet2)] UFL: Set.IsSupersetOf [is set 1 a superset of set 2][if Diff(B,A) = null set, then A is a superset of B][if A = B, then A is a superset of B (but not a proper superset of B)][note: often doable via operators] AutoHotkey: ___ C++: vIsSuperset = std::includes(oSet1.begin(), oSet1.end(), oSet2.begin(), oSet2.end()) [requires (includes): #include <algorithm>] C#: vIsSuperset = oSet1.IsSupersetOf(oSet2) [also: vIsProperSuperset = oSet1.IsProperSupersetOf(oSet2)] Crystal: vIsSuperset = oSet1.superset_of?(oSet2) [also: vIsProperSuperset = oSet1.proper_superset_of?(oSet2)] Excel: ___ Excel VBA: ___ Go: ___ Java: vIsSuperset = oSet1.containsAll(oSet2) JavaScript: vIsSuperset = oSet1.isSupersetOf(oSet2) [also: vIsSuperset = Array.from(oSet2).every(v => oSet1.has(v))] Kotlin: vIsSuperset = oSet1.containsAll(oSet2) PHP: ___ [can use (arrays): $vIsSuperset = !count(array_diff($oArray2, $oArray1))] Python: vIsSuperset = oSet1.issuperset(oSet2) [also: vIsSuperset = (oSet1 >= oSet2)] [also: vIsProperSuperset = (oSet1 > oSet2)] R: ___ [can use (vectors): vIsSuperset = !length(setdiff(oVec2, oVec1))] Ruby: vIsSuperset = oSet1.superset?(oSet2) [also: vIsSuperset = (oSet1 >= oSet2)] [also: vIsProperSuperset = oSet1.proper_superset?(oSet2)] [also: vIsProperSuperset = (oSet1 > oSet2)] Rust: vIsSuperset = oSet1.is_superset(&oSet2) Scala: vIsSuperset = oSet2.subsetOf(oSet1) SQL (MySQL): SELECT 0 = COUNT(*) FROM (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) oTemp [MAJOR WARNING: in MySQL, 'EXISTS' must be part of 'WHERE (NOT) EXISTS', unlike PostgreSQL/SQLite] [version: MySQL 8.0.31: EXCEPT added] SQL (PostgreSQL): SELECT NOT EXISTS (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) SQL (SQLite): SELECT NOT EXISTS (SELECT * FROM MyTable2 EXCEPT SELECT * FROM MyTable1) Swift: vIsSuperset = oSet1.isSuperset(of:oSet2) [also: vIsProperSuperset = oSet1.isStrictSuperset(of:oSet2)] UFL: Set.IsDisjointFrom [the intersection of set 1 and set 2 is the null set (there is no overlap, the intersection is empty)][inverse: do 2 sets overlap (is the intersection size greater than 0)] AutoHotkey: ___ C++: ___ [can use: vIsDisjoint = std::none_of(oSet1.begin(), oSet1.end(), [&oSet2](std::string v){return oSet2.count(v);})] [also: std::vector<std::string> oVecTemp; std::set_intersection(oSet1.begin(), oSet1.end(), oSet2.begin(), oSet2.end(), std::inserter(oVecTemp, oVecTemp.begin())); auto vIsDisjoint = (oVecTemp.size() == 0)] [requires (none_of/set_intersection): #include <algorithm>] C#: vIsDisjoint = !oSet1.Overlaps(oSet2) Crystal: vIsDisjoint = !oSet1.intersects?(oSet2) [inverse: oSet1.intersects?(oSet2)] Excel: ___ Excel VBA: ___ Go: ___ Java: vIsDisjoint = Collections.disjoint(oSet1, oSet2) JavaScript: vIsDisjoint = oSet1.isDisjointFrom(oSet2) [also: vIsDisjoint = !Array.from(oSet1).some(v => oSet2.has(v))] Kotlin: ___ [can use: vIsDisjoint = oSet1.none{oSet2.contains(it)}] [also: vIsDisjoint = oSet1.intersect(oSet2).isEmpty()] PHP: ___ [can use (arrays): $vIsDisjoint = !count(array_intersect($oArray1, $oArray2))] Python: vIsDisjoint = oSet1.isdisjoint(oSet2) R: ___ [can use (vectors): vIsDisjoint = !length(intersect(oVec1, oVec2))] Ruby: vIsDisjoint = oSet1.disjoint?(oSet2) Rust: vIsDisjoint = oSet1.is_disjoint(&oSet2) Scala: ___ [can use: vIsDisjoint = !oSet1.exists{oSet2.contains(_)}] [also: vIsDisjoint = oSet1.intersect(oSet2).isEmpty] SQL (MySQL): SELECT 0 = COUNT(*) FROM (SELECT 1 FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.v = t2.v) oTemp [MAJOR WARNING: in MySQL, 'EXISTS' must be part of 'WHERE (NOT) EXISTS', unlike PostgreSQL/SQLite] SQL (PostgreSQL): SELECT NOT EXISTS (SELECT 1 FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.v = t2.v) SQL (SQLite): SELECT NOT EXISTS (SELECT 1 FROM MyTable1 t1 INNER JOIN MyTable2 t2 ON t1.v == t2.v) Swift: vIsDisjoint = oSet1.isDisjoint(with:oSet2) UFL: Set.Join [join set items into one string, with a separator string between each item][WARNING: values may not be joined in insertion order][see also: Set.ToString] AutoHotkey: ___ C++: ___ [can use (string set): std::string vText = std::accumulate(std::begin(oSet), std::end(oSet), std::string(""), [&vSep](std::string a,std::string v){return a+v+vSep;})] [WARNING: adds a trailing separator] [requires (accumulate): #include <numeric>] [note: can replace '[&vSep]' with '[vSep]'] C#: vText = String.Join(vSep, oSet) Crystal: vText = oSet.join(vSep) [note: no separator if omitted] Excel: ___ Excel VBA: ___ Go: ___ Java: vText = String.join(vSep, oSet) [note: for string sets only] [also (any set): vText = oSet.stream().map(String::valueOf).collect(Collectors.joining(vSep))] [requires (Collectors): import java.util.stream.*] JavaScript: ___ [can use: vText = [...oSet].join(vSep)] [also: vText = Array.from(oSet).join(vSep)] [note: separator is comma if omitted] Kotlin: vText = oSet.joinToString(vSep) [note: separator is comma-space if omitted] PHP: ___ Python: vText = vSep.join(oSet) [WARNING: can't do: oSet.join(vSep)] [note: for string sets only] [also (any set): vText = vSep.join(map(str, oSet))] [WARNING: values may not be joined in insertion order] R: ___ Ruby: vText = oSet.join(vSep) [note: no separator if omitted] Rust: [can use: vText = oSet.iter().map(|v| format!("{}", v)).collect::<Vec<_>>().join(vSep)] [note: can't omit separator] [WARNING: values may not be joined in insertion order] Scala: ___ [can use: vText = oSet.toArray.mkString(vSep)] [WARNING: values may not be joined in insertion order] SQL (MySQL): SELECT group_concat(v ORDER BY v SEPARATOR MySep) FROM MyTable [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] SQL (PostgreSQL): SELECT string_agg(v, MySep ORDER BY v) FROM MyTable [MAJOR WARNING: see Array.Join re. combining string_agg() with 'ORDER BY'] SQL (SQLite): SELECT group_concat(v, MySep ORDER BY v) FROM MyTable [MAJOR WARNING: see Array.Join re. combining group_concat() with 'ORDER BY'] [also: string_agg()] Swift: vText = oSet.joined(separator:vSep) [note: for string sets only] [also (any set): vText = oSet.map{String($0)}.joined(separator:vSep)] [note (joined): no separator if omitted] UFL: Set.ToArray [or Set.Values][get values as an array][note: versus arrays: set values are like array values][note: versus maps: set value lookup is like map key lookup][see also: Array.ToSet] AutoHotkey: ___ C++: std::vector<std::string> oVec(oSet.begin(), oSet.end()) C#: ___ [can use: string[] oArray = new string[oSet.Count]; oSet.CopyTo(oArray)] [also: string[] oArray = oSet.ToArray()] [requires (ToArray): using System.Linq] Crystal: oArray = oSet.to_a Excel: ___ Excel VBA: ___ Go: ___ Java: oArray = oSet.toArray() JavaScript: oArray = [...oSet] [also: oArray = Array.from(oSet)] Kotlin: oArray = oSet.toTypedArray() PHP: ___ Python: oList = list(oSet) R: ___ Ruby: oArray = oSet.to_a Rust: oVec = oSet.iter().collect::<Vec<_>>() [also: oVec: Vec<_> = oSet.iter().collect()] [also: can replace iter with into_iter] [also: oVec = Vec::from_iter(oSet)] Scala: oArray = oSet.toArray SQL (MySQL): ___ [can use: CREATE TABLE MyTableNew (k INTEGER PRIMARY KEY AUTO_INCREMENT, v TEXT); INSERT INTO MyTableNew SELECT NULL,v FROM MyTable;] SQL (PostgreSQL): ___ [can use: CREATE TABLE MyTableNew (k SERIAL PRIMARY KEY, v TEXT); INSERT INTO MyTableNew (v) SELECT v FROM MyTable;] SQL (SQLite): ___ [can use: CREATE TABLE MyTableNew (k INTEGER PRIMARY KEY, v TEXT); INSERT INTO MyTableNew SELECT NULL,v FROM MyTable;] [also: CREATE TABLE MyTableNew AS SELECT rowid AS k,* FROM MyTable] [WARNING (rowid approach): assumes no gaps in rowid values] Swift: oArray = Array(oSet)
UFL: (JsonArrayDemo) [store JSON string, avoid escaping individual quotes if possible] AutoHotkey: vJson := '["a", "b", "c"]' C++: vJson = R"(["a", "b", "c"])" C#: vJson = """["a", "b", "c"]""" [also: vJson = @"[""a"", ""b"", ""c""]"] Crystal: vJson = %(["a", "b", "c"]) Excel: ["a", "b", "c"] [also: ="[""a"", ""b"", ""c""]"] Excel VBA: vJson = "[""a"", ""b"", ""c""]" Go: vJson := `["a", "b", "c"]` Java: vJson = """\u000A["a", "b", "c"]""" [also: vJson = "[\"a\", \"b\", \"c\"]"] [note: """\u000Aabc""" is equivalent to "abc", '\u000A' becomes a line break and is not included in the string] [MAJOR WARNING: Java replaces escaped chars, including in comments, before parsing the source code] JavaScript: vJson = '["a", "b", "c"]' Kotlin: vJson = """["a", "b", "c"]""" PHP: $vJson = '["a", "b", "c"]' Python: vJson = '["a", "b", "c"]' [also: vJson = """["a", "b", "c"]"""] R: vJson = '["a", "b", "c"]' Ruby: vJson = '["a", "b", "c"]' [also: vJson = %(["a", "b", "c"])] Rust: vJson = r#"["a", "b", "c"]"# Scala: vJson = """["a", "b", "c"]""" SQL (MySQL): '["a", "b", "c"]' SQL (PostgreSQL): '["a", "b", "c"]' SQL (SQLite): '["a", "b", "c"]' Swift: vJson = #"["a", "b", "c"]"# [also: vJson = "[\"a\", \"b\", \"c\"]"] UFL: (JsonObjectDemo) [store JSON string, avoid escaping individual quotes if possible][warning: for JSON strings, property names require quotes (they can be omitted when creating an object in JavaScript)] AutoHotkey: vJson := '{"p1":"v1", "p2":"v2", "p3":"v3"}' C++: vJson = R"({"p1":"v1", "p2":"v2", "p3":"v3"})" C#: vJson = """{"p1":"v1", "p2":"v2", "p3":"v3"}""" [also: vJson = @"{""p1"":""v1"", ""p2"":""v2"", ""p3"":""v3""}"] Crystal: vJson = %({"p1":"v1", "p2":"v2", "p3":"v3"}) Excel: {"p1":"v1", "p2":"v2", "p3":"v3"} [also: ="{""p1"":""v1"", ""p2"":""v2"", ""p3"":""v3""}"] Excel VBA: vJson = "{""p1"":""v1"", ""p2"":""v2"", ""p3"":""v3""}" Go: vJson := `{"p1":"v1", "p2":"v2", "p3":"v3"}` Java: vJson = """\u000A{"p1":"v1", "p2":"v2", "p3":"v3"}""" [also: vJson = "{\"p1\":\"v1\", \"p2\":\"v2\", \"p3\":\"v3\"}"] [note: """\u000Aabc""" is equivalent to "abc", '\u000A' becomes a line break and is not included in the string] [MAJOR WARNING: Java replaces escaped chars, including in comments, before parsing the source code] JavaScript: vJson = '{"p1":"v1", "p2":"v2", "p3":"v3"}' Kotlin: vJson = """{"p1":"v1", "p2":"v2", "p3":"v3"}""" PHP: $vJson = '{"p1":"v1", "p2":"v2", "p3":"v3"}' Python: vJson = '{"p1":"v1", "p2":"v2", "p3":"v3"}' [also: vJson = """{"p1":"v1", "p2":"v2", "p3":"v3"}"""] R: vJson = '{"p1":"v1", "p2":"v2", "p3":"v3"}' Ruby: vJson = '{"p1":"v1", "p2":"v2", "p3":"v3"}' [also: vJson = %({"p1":"v1", "p2":"v2", "p3":"v3"})] Rust: vJson = r#"{"p1":"v1", "p2":"v2", "p3":"v3"}"# Scala: vJson = """{"p1":"v1", "p2":"v2", "p3":"v3"}""" SQL (MySQL): '{"p1":"v1", "p2":"v2", "p3":"v3"}' SQL (PostgreSQL): '{"p1":"v1", "p2":"v2", "p3":"v3"}' SQL (SQLite): '{"p1":"v1", "p2":"v2", "p3":"v3"}' Swift: vJson = #"{"p1":"v1", "p2":"v2", "p3":"v3"}"# [also: vJson = "{\"p1\":\"v1\", \"p2\":\"v2\", \"p3\":\"v3\"}"] UFL: JsonIsValid [check if string is a valid JSON string] AutoHotkey: ___ C++: ___ C#: ___ [can use: JsonSerializer.Deserialize<dynamic>(vJson) with try/catch] Crystal: ___ [can use: JSON.parse(vJson) with rescue] [requires: require "json"] Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ [can use: JSON.parse(vJson) with try/catch] Kotlin: ___ PHP: $vBool = json_validate($vJson) Python: ___ [can use: json.loads(vJson) with try/except] [requires: import json] R: ___ Ruby: ___ [can use: JSON.parse(vJson) with rescue] [requires: require "json"] Rust: ___ Scala: ___ SQL (MySQL): json_valid(MyJson) SQL (PostgreSQL): MyJson IS JSON SQL (SQLite): json_valid(MyJson) [also (1-based index of first error, else 0): json_error_position(MyJson)] Swift: ___ [can use: JSONDecoder().decode() with do/catch] [also: e.g. JSON to int array: var oData = vJson.data(using:.utf8)!; var vBool = (try? JSONDecoder().decode([Int].self, from:oData)) != nil] [requires (data/JSONDecoder): import Foundation] UFL: JsonToObj [or ObjFromJson][JSON string to object/value][note: some programming languages, e.g. SQL variants, have: JSON string to 'JSON string as object'][see also: JsonExtractArrayDemo] AutoHotkey: ___ C++: ___ C#: dynamic oObj = JsonSerializer.Deserialize<dynamic>(vJson) [e.g. where oObj is an ExpandoObject] [requires: using System.Text.Json] Crystal: oObj = JSON.parse(vJson) [requires: require "json"] Excel: ___ Excel VBA: ___ Go: ___ [e.g. var oObj MyStruct; json.Unmarshal([]byte(vJson), &oObj)] [requires (json): import "encoding/json"] [WARNING: property names in JSON strings typically start with a lower case letter, json.Unmarshal() requires that property names in a struct start with a capital letter, workaround: use struct tags (e.g. `json:"myprop"`) in the struct definition, e.g. 'myprop' in the JSON string is mapped to 'Myprop' in the struct instance and vice versa] Java: ___ JavaScript: oObj = JSON.parse(vJson) Kotlin: ___ PHP: $oObj = json_decode($vJson) Python: oObj = json.loads(vJson) [requires: import json] R: ___ Ruby: oObj = JSON.parse(vJson) [requires: require "json"] Rust: ___ Scala: ___ SQL (MySQL): ___ [can use (to JSON object): CAST(MyJson AS JSON)] [also: to raw value as string: e.g. json_unquote(json_extract('"abc"', '$'))] SQL (PostgreSQL): ___ [can use (to JSONB object): MyJson::jsonb] [also (generally slower to read): MyJson::json] [also: to raw value as string ('::json' also works): e.g. '"abc"'::jsonb #>> '{}'] SQL (SQLite): ___ [can use (to JSONB blob object): jsonb(MyJson)] [also: to raw value: e.g. '"abc"'->>'$'] Swift: ___ [e.g. JSON to int array: var oData = vJson.data(using:.utf8)!; var oObj = try! JSONDecoder().decode([Int].self, from:oData)] [requires (data/JSONDecoder): import Foundation] UFL: JsonExtractArrayDemo [JSON string containing an array, read array value][extract data from a JSON string: get some or all of a JSON string as a value, or as a JSON string] AutoHotkey: ___ C++: ___ C#: ___ Crystal: ___ Excel: ___ Excel VBA: ___ Go: ___ Java: ___ JavaScript: ___ Kotlin: ___ PHP: ___ Python: ___ R: ___ Ruby: ___ Rust: ___ Scala: ___ SQL (MySQL): ___ [e.g. to raw value as string: json_unquote(json_extract('[1,2,3]', '$[0]'))] [e.g. to JSON object: json_extract('[1,2,3]', '$[0]')] [also: to raw value as string: oJson->>'$[0]' FROM (SELECT CAST('[1,2,3]' AS JSON) AS oJson) oTemp] [also: to JSON object: oJson->'$[0]' FROM (SELECT CAST('[1,2,3]' AS JSON) AS oJson) oTemp] SQL (PostgreSQL): ___ [e.g. to raw value as string: '[1,2,3]'::json ->> 0] [e.g. to JSON object: '[1,2,3]'::json -> 0] SQL (SQLite): ___ [e.g. to raw value: '[1,2,3]' ->> 0] [e.g. to JSON string: '[1,2,3]' -> 0] Swift: ___ UFL: JsonFromObj [or ObjToJson/Object.ToJson/Array.ToJson][array/object/value to JSON string (JSON string from array/object/value)][state whether comma or comma-space is used between array items] AutoHotkey: ___ C++: ___ C#: vJson = JsonSerializer.Serialize(oObj) [e.g. where oObj is an array or ExpandoObject] [requires: using System.Text.Json] [note: array items comma-separated] Crystal: vJson = oObj.to_json [requires (to_json): require "json"] [note: array items comma-separated] Excel: ___ Excel VBA: ___ Go: ___ [e.g. oBuf, vErr := json.Marshal(oObj); vJson := string(oBuf)] [e.g. where oObj is a slice/array or struct] [requires (json): import "encoding/json"] [WARNING: property names in JSON strings typically start with a lower case letter, json.Unmarshal() requires that property names in a struct start with a capital letter, workaround: use struct tags (e.g. `json:"myprop"`) in the struct definition, e.g. 'myprop' in the JSON string is mapped to 'Myprop' in the struct instance and vice versa] [note: array items comma-separated] Java: ___ JavaScript: vJson = JSON.stringify(oObj) [note: array items comma-separated] Kotlin: ___ PHP: $vJson = json_encode($oObj) [note: array items comma-separated] [note (arrays): array-like printed as array, map-like printed as object] Python: vJson = json.dumps(oObj) [requires: import json] [note: array items comma-space-separated] R: ___ Ruby: vJson = oObj.to_json [requires (to_json): require "json"] [note: array items comma-separated] Rust: ___ Scala: ___ SQL (MySQL): ___ [can use (from JSON object): json_unquote(MyJsonObj)] [also (from string): json_quote(MyText)] [also (from non-string value): json_unquote(CAST(MyValue AS JSON))] [also: json_unquote(json_array('abc', 'def', 'ghi'))] [also: json_unquote(json_object('k1','p1', 'k2','p2', 'k3','p3'))] [note: array items comma-space-separated] SQL (PostgreSQL): ___ [can use (from JSON/JSONB object): MyJsonObj::text] [also (from string): to_json(MyText::text)::text] [also (from value): to_json(MyValue)::text] [also: json_build_array('abc', 'def', 'ghi')::text] [also: json_object(ARRAY['k1','p1', 'k2','p2', 'k3','p3'])::text] [WARNING: array items comma-separated or comma-space-separated, what determines it is unclear: '[1,2,3]'::json::text, '[1,2,3]'::jsonb::text, array_to_json(ARRAY[1,2,3])::text, json_build_array(1,2,3)::text] [also: array_to_json()] [also (array-like to object): row_to_json()] SQL (SQLite): ___ [can use (from value/JSONB object, not bool): json_quote(MyValue)] [also: json_array('abc', 'def', 'ghi')] [also: json_object('k1','p1', 'k2','p2', 'k3','p3')] [note: array items comma-separated] Swift: var oData = try! JSONEncoder().encode(oObj); var vJson = String(data:oData, encoding:.utf8)! [requires (JSONEncoder): import Foundation] [also (as one-liner): vJson = String(data:try! JSONEncoder().encode(oObj), encoding:.utf8)!] [note: array items comma-separated]
UFL: (MakeFuncForEachDemoPrint) [e.g. print (create a function that can print any value)][example arrow function (anonymous function) (lambda function) (closure)][see also: PrintCustom/Any.TypeCustom] AutoHotkey: MyPrint := vValue => MsgBox(vValue) C++: auto MyPrint = [](int vValue) {std::cout << vValue << "\n";} C#: Action<int> MyPrint = vValue => Console.WriteLine(vValue) Crystal: MyPrint = ->(vValue: Int32) {p(vValue)} Excel: ___ Excel VBA: ___ Go: MyPrint := func(vValue int) { fmt.Println(vValue) } Java: IntConsumer MyPrint = vValue -> System.out.println(vValue) [also: Consumer<Integer> MyPrint = vValue -> System.out.println(vValue)] [requires: import java.util.function.*] JavaScript: MyPrint = vValue => console.log(vValue) [also: MyPrint = function (vValue) {console.log(vValue)}] Kotlin: var MyPrint = {vValue:Any -> println(vValue)} PHP: $MyPrint = fn($vValue) => print(var_export($vValue) . "\n") [also: $MyPrint = fn($vValue) => var_dump($vValue)] Python: MyPrint = lambda vValue : print(vValue) R: MyPrint = \(vValue) print(vValue) Ruby: MyPrint = ->(vValue) {p(vValue)} Rust: fn MyPrint (vValue:i32) -> (){println!("{}", vValue)} [note: in Rust, a function/anonymous function definition does not require a trailing semicolon] Scala: var MyPrint = (vValue:Any) => println(vValue) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyPrint: (_ vValue: Any) -> () = {vValue in print(vValue)} [also: can use 'Void' instead of '()'] UFL: (MakeFuncForEachWithIndexDemoPrintIntStr) [e.g. print pair][example arrow function (anonymous function) (lambda function) (closure)][see also: PrintCustom/Any.TypeCustom/PrintKeyValueAsPair] AutoHotkey: MyPrintIntStr := (vNum, vText) => MsgBox(vNum ": " vText) C++: auto MyPrintIntStr = [](int vNum, std::string vText) {std::apply([](auto&&... oArgs) {((std::cout << oArgs << ", "), ...);}, std::make_pair(vNum, vText)); std::cout << "\n";} [note: prints trailing separator] [requires: #include <utility>] C#: Action<int,string> MyPrintIntStr = (vNum, vText) => Console.WriteLine((vNum, vText)) Crystal: MyPrintIntStr = ->(vNum: Int32,vText: String) {p({vNum, vText})} Excel: ___ Excel VBA: ___ Go: MyPrintIntStr := func(vNum int, vText string) { fmt.Println([...]interface{}{vNum, vText}) } Java: BiConsumer<Integer,String> MyPrintIntStr = (vNum, vText) -> System.out.println(Map.entry(vNum, vText)) [requires (Map): import java.util.*] [requires: import java.util.function.*] JavaScript: MyPrintIntStr = (vNum, vText) => console.log([vNum, vText]) Kotlin: var MyPrintIntStr = {vNum:Any, vText:Any -> println(Pair(vNum, vText))} PHP: $MyPrintIntStr = fn($vNum, $vText) => print(var_export([$vNum, $vText]) . "\n") [also: $MyPrintIntStr = fn($vNum, $vText) => var_dump([$vNum, $vText])] Python: MyPrintIntStr = lambda vNum, vText : print((vNum, vText)) R: MyPrintIntStr = \(vNum,vText) print(list(vNum, vText)) Ruby: MyPrintIntStr = ->(vNum,vText) {p([vNum, vText])} Rust: fn MyPrintIntStr (vNum:i32, vText:String) -> (){println!("{:?}", (vNum, vText))} [note: in Rust, a function/anonymous function definition does not require a trailing semicolon] [note: array indexes have type usize, use 'as i32' to convert them] Scala: var MyPrintIntStr = (vNum:Any,vText:Any) => println((vNum, vText)) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyPrintIntStr: (_ vNum:Any, _ vText:Any) -> () = {vNum,vText in print((vNum, vText))} [also: can use 'Void' instead of '()']
UFL: (MakeFuncMapDemoDouble) [e.g. double][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyDouble := vNum => vNum*2 C++: auto MyDouble = [](int vNum) {return vNum*2;} C#: Func<int,int> MyDouble = vNum => vNum*2 Crystal: MyDouble = ->(vNum: Int32) {vNum*2} Excel: ___ Excel VBA: ___ Go: MyDouble := func(vNum int) int { return vNum * 2 } Java: Function<Integer,Integer> MyDouble = vNum -> vNum*2 [also: UnaryOperator<Integer> MyDouble = vNum -> vNum*2] [also (e.g. MyDouble.applyAsInt()): ToIntFunction<Integer> MyDouble = vNum -> vNum*2] [requires: import java.util.function.*] JavaScript: MyDouble = vNum => vNum*2 [also: MyDouble = function (v) {return v*2}] Kotlin: var MyDouble = {vNum:Int -> vNum*2} PHP: $MyDouble = fn($vNum) => $vNum*2 Python: MyDouble = lambda vNum : vNum*2 R: MyDouble = \(vNum) vNum*2 Ruby: MyDouble = ->(vNum) {vNum*2} Rust: fn MyDouble (vNum:i32) -> i32{vNum*2} [note: in Rust, a function/anonymous function definition does not require a trailing semicolon] Scala: var MyDouble = (vNum:Int) => vNum*2 SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyDouble: (_ vNum: Int) -> Int = {vNum in vNum*2} UFL: (MakeFuncMapDemoDoubleStr) [e.g. concatenate a string to itself][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyDoubleStr := vText => vText vText C++: auto MyDoubleStr = [](std::string vText) {return vText+vText;} C#: Func<string,string> MyDoubleStr = vText => vText + vText Crystal: MyDoubleStr = ->(vText: String) {vText + vText} Excel: ___ Excel VBA: ___ Go: MyDoubleStr := func(vText string) string { return vText + vText } Java: Function<String,String> MyDoubleStr = vText -> vText + vText [requires: import java.util.function.*] JavaScript: MyDoubleStr = vText => "" + vText + vText Kotlin: var MyDoubleStr = {vText:String -> vText+vText} PHP: $MyDoubleStr = fn($vText) => $vText . $vText Python: MyDoubleStr = lambda vText : vText + vText R: MyDoubleStr = \(vText) paste0(vText, vText) Ruby: MyDoubleStr = ->(vText) {vText + vText} Rust: fn MyDoubleStr (vText:String) -> String{format!("{}{}", vText, vText)} Scala: var MyDoubleStr = (vText:String) => vText + vText SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyDoubleStr: (_ vText:String) -> String = {vText in vText + vText} UFL: (MakeFuncMapDemoRept3) [e.g. create an array, repeat the value 3 times][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyRept3 := vValue => [vValue, vValue, vValue] C++: auto MyRept3 = [](int vValue) {return std::vector<int>{vValue, vValue, vValue};} C#: Func<int,int[]> MyRept3 = vValue => Enumerable.Repeat(vValue, 3).ToArray() [requires (Enumerable): using System.Linq] Crystal: MyRept3 = ->(vValue: Int32) {Array.new(3, vValue)} Excel: ___ Excel VBA: ___ Go: MyRept3 := func(vValue int) []int { return []int{vValue, vValue, vValue} } Java: Function<Integer,int[]> MyRept3 = vValue -> Collections.nCopies(3, vValue).stream().mapToInt(v->v).toArray() [requires: import java.util.function.*] JavaScript: MyRept3 = vValue => Array(3).fill(vValue) Kotlin: var MyRept3 = {vValue:Int -> Array(3){vValue}} [also: var MyRept3 = {vValue:Int -> List(3){vValue}}] PHP: $MyRept3 = fn($vValue) => array_fill(0, 3, $vValue) Python: MyRept3 = lambda vValue : [vValue] * 3 R: MyRept3 = \(vValue) rep(vValue, 3) Ruby: MyRept3 = ->(vValue) {Array.new(3, vValue)} Rust: fn MyRept3 (vValue:i32) -> Vec<i32>{vec![vValue; 3]} Scala: var MyRept3 = (vValue:Int) => Array.fill(3)(vValue) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyRept3: (_ vValue: Int) -> [Int] = {vValue in Array(repeating:vValue, count:3)} UFL: (MakeFuncMapDemoLen) [e.g. string get length][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyLen := vText => StrLen(vText) C++: auto MyLen = [](std::string vText) {return vText.size();} C#: Func<string,int> MyLen = vText => vText.Length Crystal: MyLen = ->(vText: String) {vText.size} Excel: ___ Excel VBA: ___ Go: MyLen := func(vText string) int { return len(vText) } Java: Function<String,Integer> MyLen = vText -> vText.length() [also (e.g. MyLen.applyAsInt()): ToIntFunction<String> MyLen = vText -> vText.length()] [requires: import java.util.function.*] JavaScript: MyLen = vText => vText.length Kotlin: var MyLen = {vText:String -> vText.length} PHP: $MyLen = fn($vText) => strlen($vText) Python: MyLen = lambda vText : len(vText) R: MyLen = \(vText) nchar(vText) Ruby: MyLen = ->(vText) {vText.length} Rust: fn MyLen (vText:String) -> i32{vText.len() as i32} Scala: var MyLen = (vText:String) => vText.length SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyLen: (_ vText: String) -> Int = {vText in vText.count} UFL: (MakeFuncMapWithIndexDemoNumConcat) [e.g. 'concatenate' key/value][input key/value, output new value][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyNumConcat := (vNum1, vNum2) => vNum1*1000 + vNum2 C++: auto MyNumConcat = [](int vNum1, int vNum2) {return vNum1*1000 + vNum2;} C#: Func<int,int,int> MyNumConcat = (vNum1, vNum2) => vNum1*1000 + vNum2 [also: modified version: value/key param order, for use with Select: Func<int,int,int> MyNumConcatMod = (vValue, vKey) => vKey*1000 + vValue] Crystal: MyNumConcat = ->(vNum1: Int32,vNum2: Int32) {vNum1*1000 + vNum2} [also: modified version: tuple (value/key param order), for use with map: MyNumConcatMod = ->(oTupleVK: {Int32,Int32}) {oTupleVK[1]*1000 + oTupleVK[0]}] Excel: ___ Excel VBA: ___ Go: MyNumConcat := func(vNum1, vNum2 int) int { return vNum1*1000 + vNum2 } Java: BinaryOperator<Integer> MyNumConcat = (vNum1, vNum2) -> vNum1*1000 + vNum2 [requires: import java.util.function.*] JavaScript: MyNumConcat = (vNum1, vNum2) => vNum1*1000 + vNum2 [also: modified version: value/key param order, for use with map: MyNumConcatMod = (vValue, vKey) => vKey*1000 + vValue] Kotlin: var MyNumConcat = {vNum1:Int, vNum2:Int -> vNum1*1000 + vNum2} PHP: $MyNumConcat = fn($vNum1, $vNum2) => $vNum1*1000 + $vNum2 Python: MyNumConcat = lambda vNum1, vNum2 : vNum1*1000 + vNum2 R: MyNumConcat = \(vNum1,vNum2) vNum1*1000 + vNum2 Ruby: MyNumConcat = ->(vNum1,vNum2) {vNum1*1000 + vNum2} [also: modified version: value/key param order, for use with map: MyNumConcatMod = ->(vValue,vKey) {vKey*1000 + vValue}] Rust: fn MyNumConcat (vNum1:i32, vNum2:i32) -> i32{vNum1*1000 + vNum2} Scala: var MyNumConcat = (vNum1:Int, vNum2:Int) => vNum1*1000 + vNum2 [also: modified version: tuple (value/key param order), for use with map: var MyNumConcatMod = (oTupleVK:(Int,Int)) => oTupleVK._2*1000 + oTupleVK._1] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyNumConcat: (_ vNum1:Int, _ vNum2:Int) -> Int = {vNum1,vNum2 in vNum1*1000 + vNum2}
UFL: (MakeFuncReduceDemoAdd) [e.g. add, useful for sum][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyAdd := (vNum1, vNum2) => vNum1 + vNum2 C++: auto MyAdd = [](int vNum1, int vNum2) {return vNum1+vNum2;} C#: Func<int,int,int> MyAdd = (vNum1, vNum2) => vNum1 + vNum2 Crystal: MyAdd = ->(vNum1: Int32,vNum2: Int32) {vNum1+vNum2} Excel: ___ Excel VBA: ___ Go: MyAdd := func(vNum1, vNum2 int) int { return vNum1 + vNum2 } Java: BinaryOperator<Integer> MyAdd = (vNum1, vNum2) -> vNum1 + vNum2 [requires: import java.util.function.*] JavaScript: MyAdd = (vNum1, vNum2) => vNum1 + vNum2 [also: MyAdd = function (v1,v2) {return v1+v2}] Kotlin: var MyAdd = {vNum1:Int, vNum2:Int -> vNum1+vNum2} PHP: $MyAdd = fn($vNum1, $vNum2) => $vNum1 + $vNum2 Python: MyAdd = lambda vNum1, vNum2 : vNum1 + vNum2 R: MyAdd = \(vNum1,vNum2) vNum1+vNum2 Ruby: MyAdd = ->(vNum1,vNum2) {vNum1+vNum2} Rust: fn MyAdd (vNum1:i32, vNum2:i32) -> i32{vNum1+vNum2} Scala: var MyAdd = (vNum1:Int, vNum2:Int) => vNum1 + vNum2 SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyAdd: (_ vNum1:Int, _ vNum2:Int) -> Int = {vNum1,vNum2 in vNum1+vNum2} UFL: (MakeFuncReduceDemoSub) [e.g. subtract][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MySub := (vNum1, vNum2) => vNum1 - vNum2 C++: auto MySub = [](int vNum1, int vNum2) {return vNum1-vNum2;} C#: Func<int,int,int> MySub = (vNum1, vNum2) => vNum1 - vNum2 Crystal: MySub = ->(vNum1: Int32,vNum2: Int32) {vNum1-vNum2} Excel: ___ Excel VBA: ___ Go: MySub := func(vNum1, vNum2 int) int { return vNum1 - vNum2 } Java: BinaryOperator<Integer> MySub = (vNum1, vNum2) -> vNum1 - vNum2 [requires: import java.util.function.*] JavaScript: MySub = (vNum1, vNum2) => vNum1 - vNum2 Kotlin: var MySub = {vNum1:Int, vNum2:Int -> vNum1-vNum2} PHP: $MySub = fn($vNum1, $vNum2) => $vNum1 - $vNum2 Python: MySub = lambda vNum1, vNum2 : vNum1 - vNum2 R: MySub = \(vNum1,vNum2) vNum1-vNum2 Ruby: MySub = ->(vNum1,vNum2) {vNum1-vNum2} Rust: fn MySub (vNum1:i32, vNum2:i32) -> i32{vNum1-vNum2} Scala: var MySub = (vNum1:Int, vNum2:Int) => vNum1 - vNum2 SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MySub: (_ vNum1:Int, _ vNum2:Int) -> Int = {vNum1,vNum2 in vNum1-vNum2} UFL: (MakeFuncReduceDemoMul) [e.g. multiply, useful for product][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyMul := (vNum1, vNum2) => vNum1 * vNum2 C++: auto MyMul = [](int vNum1, int vNum2) {return vNum1*vNum2;} C#: Func<int,int,int> MyMul = (vNum1, vNum2) => vNum1 * vNum2 Crystal: MyMul = ->(vNum1: Int32,vNum2: Int32) {vNum1*vNum2} Excel: ___ Excel VBA: ___ Go: MyMul := func(vNum1, vNum2 int) int { return vNum1 * vNum2 } Java: BinaryOperator<Integer> MyMul = (vNum1, vNum2) -> vNum1 * vNum2 [requires: import java.util.function.*] JavaScript: MyMul = (vNum1, vNum2) => vNum1 * vNum2 Kotlin: var MyMul = {vNum1:Int, vNum2:Int -> vNum1*vNum2} PHP: $MyMul = fn($vNum1, $vNum2) => $vNum1 * $vNum2 Python: MyMul = lambda vNum1, vNum2 : vNum1 * vNum2 R: MyMul = \(vNum1,vNum2) vNum1*vNum2 Ruby: MyMul = ->(vNum1,vNum2) {vNum1*vNum2} Rust: fn MyMul (vNum1:i32, vNum2:i32) -> i32{vNum1*vNum2} Scala: var MyMul = (vNum1:Int, vNum2:Int) => vNum1 * vNum2 SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyMul: (_ vNum1:Int, _ vNum2:Int) -> Int = {vNum1,vNum2 in vNum1*vNum2} UFL: (MakeFuncReduceDemoDivI) [e.g. true division (ints to double)][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyDivI := (vNum1, vNum2) => vNum1 / vNum2 C++: auto MyDivI = [](int vNum1, int vNum2) {return vNum1/(double)vNum2;} C#: Func<int,int,double> MyDivI = (vNum1, vNum2) => vNum1 / (double)vNum2 Crystal: MyDivI = ->(vNum1: Int32,vNum2: Int32) {vNum1/vNum2} Excel: ___ Excel VBA: ___ Go: MyDivI := func(vNum1, vNum2 int) float64 { return float64(vNum1) / float64(vNum2) } Java: BiFunction<Integer,Integer,Double> MyDivI = (vNum1, vNum2) -> vNum1 / (double)vNum2 [also: ToDoubleBiFunction<Integer,Integer> MyDivIX = (vNum1, vNum2) -> vNum1 / (double)vNum2] [requires: import java.util.function.*] JavaScript: MyDivI = (vNum1, vNum2) => vNum1 / vNum2 Kotlin: var MyDivI = {vNum1:Int, vNum2:Int -> vNum1/vNum2.toDouble()} PHP: $MyDivI = fn($vNum1, $vNum2) => $vNum1 / $vNum2 Python: MyDivI = lambda vNum1, vNum2 : vNum1 / vNum2 R: MyDivI = \(vNum1,vNum2) vNum1/vNum2 Ruby: MyDivI = ->(vNum1,vNum2) {vNum1/vNum2.to_f} Rust: fn MyDivI (vNum1:i32, vNum2:i32) -> f64{vNum1 as f64/vNum2 as f64} Scala: var MyDivI = (vNum1:Int, vNum2:Int) => vNum1 / vNum2.toDouble SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyDivI: (_ vNum1:Int, _ vNum2:Int) -> Double = {vNum1,vNum2 in Double(vNum1)/Double(vNum2)} UFL: (MakeFuncReduceDemoDivF) [e.g. true division (doubles to double)][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyDivF := (vNum1, vNum2) => vNum1 / vNum2 C++: auto MyDivF = [](double vNum1, double vNum2) {return vNum1/vNum2;} C#: Func<double,double,double> MyDivF = (vNum1, vNum2) => vNum1 / vNum2 Crystal: MyDivF = ->(vNum1: Float64,vNum2: Float64) {vNum1/vNum2} Excel: ___ Excel VBA: ___ Go: MyDivF := func(vNum1, vNum2 float64) float64 { return vNum1 / vNum2 } Java: BinaryOperator<Double> MyDivF = (vNum1, vNum2) -> vNum1 / vNum2 [requires: import java.util.function.*] JavaScript: MyDivF = (vNum1, vNum2) => vNum1 / vNum2 [also: MyDivF = function (v1,v2) {return v1/v2}] Kotlin: var MyDivF = {vNum1:Double, vNum2:Double -> vNum1/vNum2} PHP: $MyDivF = fn($vNum1, $vNum2) => $vNum1 / $vNum2 Python: MyDivF = lambda vNum1, vNum2 : vNum1 / vNum2 R: MyDivF = \(vNum1,vNum2) vNum1/vNum2 Ruby: MyDivF = ->(vNum1,vNum2) {vNum1/vNum2.to_f} Rust: fn MyDivF (vNum1:f64, vNum2:f64) -> f64{vNum1/vNum2} Scala: var MyDivF = (vNum1:Double, vNum2:Double) => vNum1 / vNum2 SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyDivF: (_ vNum1:Double, _ vNum2:Double) -> Double = {vNum1,vNum2 in vNum1/vNum2} UFL: (MakeFuncReduceDemoConcat) [e.g. concat 2 strings][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyConcat := (vText1, vText2) => vText1 vText2 C++: auto MyConcat = [](std::string vText1, std::string vText2) {return vText1+vText2;} C#: Func<string,string,string> MyConcat = (vText1, vText2) => vText1 + vText2 Crystal: MyConcat = ->(vText1: String,vText2: String) {vText1 + vText2} Excel: ___ Excel VBA: ___ Go: MyConcat := func(vText1 string, vText2 string) string { return vText1 + vText2 } Java: BiFunction<String,String,String> MyConcat = (vText1, vText2) -> vText1 + vText2 [requires: import java.util.function.*] JavaScript: MyConcat = (vText1, vText2) => "" + vText1 + vText2 Kotlin: var MyConcat = {vText1:String, vText2:String -> vText1+vText2} PHP: $MyConcat = fn($vText1, $vText2) => $vText1 . $vText2 Python: MyConcat = lambda vText1, vText2 : vText1 + vText2 R: MyConcat = \(vText1,vText2) paste0(vText1, vText2) Ruby: MyConcat = ->(vText1,vText2) {vText1 + vText2} Rust: fn MyConcat (vText1:String, vText2:String) -> String{format!("{}{}", vText1, vText2)} [e.g. vRet = oArray.iter().fold("".to_string(), |a,v| MyConcat(a,v.to_string()))] Scala: var MyConcat = (vText1:String, vText2:String) => vText1 + vText2 SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyConcat: (_ vText1:String, _ vText2:String) -> String = {vText1,vText2 in vText1 + vText2} UFL: (MakeFuncReduceDemoConcatStrInt) [e.g. concat string and int][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyConcatStrInt := (vText, vNum) => vText vNum C++: auto MyConcatStrInt = [](std::string vText, int vNum) {return vText+std::to_string(vNum);} C#: Func<string,int,string> MyConcatStrInt = (vText, vNum) => vText + vNum Crystal: MyConcatStrInt = ->(vText: String,vNum: Int32) {vText + vNum.to_s} Excel: ___ Excel VBA: ___ Go: MyConcatStrInt := func(vText string, vNum int) string { return vText + strconv.Itoa(vNum) } Java: BiFunction<String,Integer,String> MyConcatStrInt = (vText, vNum) -> vText + vNum [requires: import java.util.function.*] [e.g. (note: combiner param used since multiple types used): vRet = Arrays.stream(oArray).boxed().reduce("", MyConcatStrInt, String::concat)] JavaScript: MyConcatStrInt = (vText, vNum) => "" + vText + vNum Kotlin: var MyConcatStrInt = {vText:String, vNum:Int -> vText+vNum} PHP: $MyConcatStrInt = fn($vText, $vNum) => $vText . $vNum Python: MyConcatStrInt = lambda vText, vNum : vText + str(vNum) R: MyConcatStrInt = \(vText,vNum) paste0(vText, vNum) Ruby: MyConcatStrInt = ->(vText,vNum) {vText + vNum.to_s} Rust: fn MyConcatStrInt (vText:String, vNum:i32) -> String{format!("{}{}", vText, vNum)} [e.g. vRet = oArray.iter().fold("".to_string(), |a,v| MyConcatStrInt(a,*v))] Scala: var MyConcatStrInt = (vText:String, vNum:Int) => vText + vNum SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyConcatStrInt: (_ vText:String, _ vNum:Int) -> String = {vText,vNum in vText + String(vNum)} UFL: (MakeFuncReduceDemoAddNumLen) [e.g. take int add string length][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyAddNumLen := (vNum, vText) => vNum + StrLen(vText) C++: auto MyAddNumLen = [](int vNum, std::string vText) {return vNum+vText.length();} C#: Func<int,string,int> MyAddNumLen = (vNum, vText) => vNum + vText.Length Crystal: MyAddNumLen = ->(vNum: Int32,vText: String) {vNum + vText.size} Excel: ___ Excel VBA: ___ Go: MyAddNumLen := func(vNum int, vText string) int { return vNum + len(vText) } Java: BiFunction<Integer,String,Integer> MyAddNumLen = (vNum, vText) -> vNum + vText.length() [requires: import java.util.function.*] [e.g. (note: combiner param used since multiple types used): vRet = Arrays.stream(oArray).reduce(0, MyAddNumLen, Integer::sum)] JavaScript: MyAddNumLen = (vNum, vText) => vNum + vText.length Kotlin: var MyAddNumLen = {vNum:Int, vText:String -> vNum+vText.length} PHP: $MyAddNumLen = fn($vNum, $vText) => $vNum + strlen($vText) Python: MyAddNumLen = lambda vNum, vText : vNum + len(vText) R: MyAddNumLen = \(vNum,vText) vNum + nchar(vText) Ruby: MyAddNumLen = ->(vNum,vText) {vNum + vText.length} Rust: fn MyAddNumLen (vNum:i32, vText:String) -> i32{vNum+vText.len() as i32} [e.g. vRet = oArray.iter().fold(0, |a,v| MyAddNumLen(a,(*v).to_string()))] Scala: var MyAddNumLen = (vNum:Int, vText:String) => vNum + vText.length SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyAddNumLen: (_ vNum:Int, _ vText:String) -> Int = {vNum,vText in vNum+vText.count} UFL: (MakeFuncReduceWithIndexDemoAccumNumConcat) [e.g. 'concatenate' key/value, add to accumulator][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyAccumNumConcat := (vAccum, vNum1, vNum2) => vAccum + vNum1*1000 + vNum2 C++: auto MyAccumNumConcat = [](int vAccum, int vNum1, int vNum2) {return vAccum+vNum1*1000+vNum2;} C#: Func<int,int,int,int> MyAccumNumConcat = (vAccum, vNum1, vNum2) => vAccum + vNum1*1000 + vNum2 Crystal: MyAccumNumConcat = ->(vAccum: Int32,vNum1: Int32,vNum2: Int32) {vAccum+vNum1*1000+vNum2} Excel: ___ Excel VBA: ___ Go: MyAccumNumConcat := func(vAccum, vNum1, vNum2 int) int { return vAccum + vNum1*1000 + vNum2 } Java: MyTriFunction<Integer,Integer,Integer,Integer> MyAccumNumConcat = (vAccum, vNum1, vNum2) -> vAccum + vNum1*1000 + vNum2 [requires: import java.util.function.*] [note: using a custom interface, see 'MyTriFunction' lower down] JavaScript: MyAccumNumConcat = (vAccum, vNum1, vNum2) => vAccum + vNum1*1000 + vNum2 [also: modified version: accum/value/key param order, for use with reduce: MyAccumNumConcatMod = (vAccum, vValue, vKey) => vAccum + vKey*1000 + vValue] Kotlin: var MyAccumNumConcat = {vAccum:Int, vNum1:Int, vNum2:Int -> vAccum + vNum1*1000+vNum2} [also: modified version: key/accum/value param order, for use with foldIndexed: MyAccumNumConcatMod = {vNum1:Int, vAccum:Int, vNum2:Int -> vAccum + vNum1*1000+vNum2}] PHP: $MyAccumNumConcat = fn($vAccum, $vNum1, $vNum2) => $vAccum + $vNum1*1000 + $vNum2 Python: MyAccumNumConcat = lambda vAccum, vNum1, vNum2 : vAccum + vNum1*1000 + vNum2 R: MyAccumNumConcat = \(vAccum,vNum1,vNum2) vAccum + vNum1*1000 + vNum2 Ruby: MyAccumNumConcat = ->(vAccum,vNum1,vNum2) {vAccum + vNum1*1000 + vNum2} Rust: fn MyAccumNumConcat (vAccum:i32, vNum1:i32, vNum2:i32) -> i32{vAccum+vNum1*1000+vNum2} Scala: var MyAccumNumConcat = (vAccum:Int, vNum1:Int, vNum2:Int) => vAccum + vNum1*1000 + vNum2 SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyAccumNumConcat: (_ vAccum:Int, _ vNum1:Int, _ vNum2:Int) -> Int = {vAccum,vNum1,vNum2 in vAccum+vNum1*1000+vNum2}
UFL: (MakeFuncFilterDemoIsValue) [e.g. is value equal to value][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyIsValue := vNum => (vNum == 123) C++: auto MyIsValue = [](int vNum) {return vNum == 123;} C#: Func<int,Boolean> MyIsValue = vNum => (vNum == 123) [also: Predicate<int> MyIsValue = vNum => (vNum == 123)] Crystal: MyIsValue = ->(vNum: Int32) {vNum == 123} Excel: ___ Excel VBA: ___ Go: MyIsValue := func(vNum int) bool { return vNum == 123 } Java: Predicate<Integer> MyIsValue = vNum -> (vNum == 123) [also: IntPredicate MyIsValue = vNum -> (vNum == 123)] [requires: import java.util.function.*] JavaScript: MyIsValue = vNum => (vNum == 123) [also: MyIsValue = function (v) {return v==123}] Kotlin: var MyIsValue = {vNum: Int -> (vNum == 123)} PHP: $MyIsValue = fn($vNum) => ($vNum == 123) Python: MyIsValue = lambda vNum : (vNum == 123) R: MyIsValue = \(vNum) (vNum == 123) Ruby: MyIsValue = ->(vNum) {vNum == 123} Rust: fn MyIsValue (vNum:i32) -> bool{vNum == 123} Scala: var MyIsValue = (vNum:Int) => (vNum == 123) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyIsValue: (_ vNum: Int) -> Bool = {vNum in vNum == 123} UFL: (MakeFuncFilterDemoIsDivisibleBy3) [e.g. is divisible by 3][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyIsDivisibleBy3 := vNum => (Mod(vNum,3) == 0) C++: auto MyIsDivisibleBy3 = [](int vNum) {return vNum%3 == 0;} C#: Func<int,Boolean> MyIsDivisibleBy3 = vNum => (vNum%3 == 0) [also: Predicate<int> MyIsDivisibleBy3 = vNum => (vNum%3 == 0)] Crystal: MyIsDivisibleBy3 = ->(vNum: Int32) {vNum%3 == 0} Excel: ___ Excel VBA: ___ Go: MyIsDivisibleBy3 := func(vNum int) bool { return vNum%3 == 0 } Java: Predicate<Integer> MyIsDivisibleBy3 = vNum -> (vNum%3 == 0) [also: IntPredicate MyIsDivisibleBy3 = vNum -> (vNum%3 == 0)] [requires: import java.util.function.*] JavaScript: MyIsDivisibleBy3 = vNum => (vNum%3 == 0) [also: MyIsDivisibleBy3 = function (v) {return v%3==0}] Kotlin: var MyIsDivisibleBy3 = {vNum: Int -> (vNum%3 == 0)} PHP: $MyIsDivisibleBy3 = fn($vNum) => ($vNum%3 == 0) Python: MyIsDivisibleBy3 = lambda vNum : (vNum%3 == 0) R: MyIsDivisibleBy3 = \(vNum) (vNum%%3 == 0) Ruby: MyIsDivisibleBy3 = ->(vNum) {vNum%3 == 0} Rust: fn MyIsDivisibleBy3 (vNum:i32) -> bool{vNum%3 == 0} Scala: var MyIsDivisibleBy3 = (vNum:Int) => (vNum%3 == 0) SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyIsDivisibleBy3: (_ vNum: Int) -> Bool = {vNum in vNum%3 == 0} UFL: (MakeFuncFilterWithIndexDemoAreEqual) [e.g. does key equal value][example arrow function (anonymous function) (lambda function) (closure)] AutoHotkey: MyAreEqual := (vNum1, vNum2) => vNum1 == vNum2 C++: auto MyAreEqual = [](int vNum1, int vNum2) {return vNum1==vNum2;} C#: Func<int,int,Boolean> MyAreEqual = (vNum1, vNum2) => vNum1 == vNum2 Crystal: MyAreEqual = ->(vNum1: Int32,vNum2: Int32) {vNum1 == vNum2} [also: modified version: tuple (value/key param order), for use with select: MyAreEqualMod = ->(oTuple: {Int32,Int32}) {oTuple[0] == oTuple[1]}] Excel: ___ Excel VBA: ___ Go: MyAreEqual := func(vNum1, vNum2 int) bool { return vNum1 == vNum2 } Java: BiPredicate<Integer,Integer> MyAreEqual = (vNum1, vNum2) -> vNum1 == vNum2 [requires: import java.util.function.*] JavaScript: MyAreEqual = (vNum1, vNum2) => vNum1 == vNum2 Kotlin: var MyAreEqual = {vNum1:Int, vNum2:Int -> vNum1==vNum2} PHP: $MyAreEqual = fn($vNum1, $vNum2) => $vNum1 == $vNum2 Python: MyAreEqual = lambda vNum1, vNum2 : vNum1 == vNum2 R: MyAreEqual = \(vNum1,vNum2) (vNum1 == vNum2) Ruby: MyAreEqual = ->(vNum1,vNum2) {vNum1 == vNum2} Rust: fn MyAreEqual (vNum1:i32, vNum2:i32) -> bool{vNum1 == vNum2} Scala: var MyAreEqual = (vNum1:Int, vNum2:Int) => vNum1 == vNum2 [also: modified version: tuple (value/key param order), for use with select: var MyAreEqualMod = MyAreEqual.tupled] [also: var MyAreEqualMod = (oTuple:(Int,Int)) => oTuple._1 == oTuple._2] SQL (MySQL): ___ SQL (PostgreSQL): ___ SQL (SQLite): ___ Swift: var MyAreEqual: (_ vNum1:Int, _ vNum2:Int) -> Bool = {vNum1,vNum2 in vNum1==vNum2}
The main imports/includes needed for these (and other) code examples: [AutoHotkey] [C++] #include <iostream> //for std::cout //classic types (std::string, std::vector, std::map): #include <string> //for std::stoi, std::to_string #include <vector> #include <map> #include <ranges> //further types (std::list, std::tuple, std::unordered_set): #include <array> #include <list> #include <sstream> //for std::stringstream #include <unordered_set> #include <tuple> //for std::apply, std::make_tuple #include <utility> //for std::pair/std::make_pair #include <set> //further: #include <algorithm> //for std::all_of/std::any_of/std::none_of, std::copy_if/std::find_if/std::remove_if, std::equal, std::fill, std::for_each, std::iter_swap, std::max/std::min, std::partition, std::reverse, std::shuffle, std::sort, std::transform, std::unique #include <bitset> #include <cassert> //for assert #include <chrono> #include <format> //for std::format #include <functional> //for std::bind #include <iomanip> //for std::setprecision #include <iostream> //for std::cout #include <limits> #include <numeric> //for std::accumulate, std::iota #include <random> //for std::mt19937, std::random_device #include <regex> #include <stdexcept> //for std::exception #include <thread> #include <type_traits> //for std::is_array, std::is_fundamental, std::is_same various: std::begin/std::end std::back_inserter std::get std::multiplies std::numeric_limits std::swap [C#] using System; using System.Linq; using System.Collections.Generic; using System.Dynamic; //for ExpandoObject //note: if use 'var' (instead of 'Dictionary') and 'ToDictionary', it appears that System.Collections.Generic is not needed (although System.Linq is) //further: using System.Collections; using System.Diagnostics; using System.Text.Json; using System.Text.RegularExpressions; using System.Text; //for StringBuilder [Crystal] require "json" require "spec" [Excel] [Excel VBA] [Go] import "cmp" import "fmt" import "math" import "math/big" import "math/bits" import "reflect" import "regexp" import "runtime" import "strconv" import "time" import "unicode/utf16" [Java] import java.util.*; import java.util.stream.*; //further: import java.lang.reflect.Field; import java.math.BigInteger; import java.text.*; import java.util.function.*; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.MatchResult; import java.util.regex.Pattern; [JavaScript] [Kotlin] import kotlin.math.roundToInt import kotlin.math.roundToLong import kotlin.math.withSign import kotlin.test.assertEquals [PHP] 'PHP must be compiled with GMP support by using the --with-gmp option' 'have to compile PHP with --enable-calendar' [Python] from types import SimpleNamespace from functools import reduce from itertools import groupby #further: from collections import defaultdict from functools import cmp_to_key import calendar import copy import datetime import itertools import json import locale import math import operator import os import platform import random import re import statistics import sys import textwrap import time import zoneinfo #further: import collections import functools import threading import types #don't require import: e.g. dict, int, list, str [R] [Ruby] include Test::Unit::Assertions require "json" require "prime" require "set" require "test/unit/assertions" [Rust] #![allow(non_snake_case)] //stop nags regarding snake_case variable names //further: use chrono::prelude::*; use itertools::Itertools use rand::prelude::*; use rand::seq::SliceRandom; use rand::thread_rng; use regex::Regex; use rustc_version::{version}; use std::any::type_name_of_val; use std::cell::RefCell; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::env; use std::process; use std::rc::Rc; use std::time; use std::{thread, time}; use version_check::Version; [Scala] import scala.util.control.Breaks._ import scala.util.matching.Regex import scala.util.Random [SQL (MySQL)] set sql_mode=PIPES_AS_CONCAT 'You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)' [stored functions] [SQL (PostgreSQL)] [SQL (SQLite)] .nullvalue NULL 'The generate_series(START,STOP,STEP) table-valued function is a loadable extension' [Swift] import Foundation
[general][indexes] Array indexes and string character indexes: Be aware of what happens when you go beyond bounds. Index below 0 (or below 1 if 1-indexed), possibilities: treated as min index, invalid index so throws, null returned, treated as negative offset from end. Index too large, possibilities: treated as max index, invalid index so throws, null returned. [C++][specifying begin/end] There are various functions where these 2 approaches are interchangeable: MyFunc(oArray, oArray+sizeof(oArray)/sizeof(oArray[0])) MyFunc(std::begin(oArray), std::end(oArray)) And where these 2 approaches are interchangeable: MyFunc(oVec.begin(), oVec.end()) MyFunc(std::begin(oVec), std::end(oVec)) E.g. functions: std::accumulate/std::partition/std::transform, std::copy, std::equal, std::fill, std::find, std::max_element/std::min_element, std::reverse/std::shuffle/std::sort. Further functions: std::copy_if/std::remove_if, std::iota. [Java][int/Integer arrrays] [int array to Integer array] int[] oArray = {1, 2, 3}; Integer[] oArrayNew = Arrays.stream(oArray).boxed().toArray(Integer[]::new); [Integer array to int array] Integer[] oArray = {1, 2, 3}; int[] oArrayNew = Arrays.stream(oArray).mapToInt(v->v).toArray(); [R][vectors/lists] [vector to list] oVec = c("a", "b", "c") oList = as.list(oVec) [list to vector] oList = list("a", "b", "c") oVec = unlist(oList) [R][custom sort orders for lists/vectors]
#R: custom sort orders for lists/vectors: #use a custom class to sort list/vector elements by string length: #based on: #Custom comparison function for sorting data in R | R-bloggers #https://www.r-bloggers.com/2017/04/custom-comparison-function-for-sorting-data-in-r/ '[.MyClass' = function(oObj, vKey) { #temporarily make it a list, to avoid an infinite loop when read value: class(oObj) = "list" oObj = oObj[vKey] class(oObj) = "MyClass" oObj } '>.MyClass' = function(oObj1, oObj2) { vValue1 = oObj1[[1]] vValue2 = oObj2[[1]] vLen1 = nchar(vValue1) vLen2 = nchar(vValue2) ifelse(vLen1 > vLen2, TRUE, FALSE) } #compare using our custom '>' above: '==.MyClass' = function(o1, o2) ifelse(o1 > o2 || o2 > o1, FALSE, TRUE) #compare using our custom '>' above: '<.MyClass' = function(o1, o2) o2 > o1 #sort a list: oList = list("a", "bb", "ccc", "d", "ee", "fff", "aa") #oList = list(1, 22, 333, 4, 55, 666, 11) print(unlist(oList)) #unsorted class(oList) = "MyClass" oList = sort(oList) class(oList) = "list" print(unlist(oList)) #custom order (string length) oList = oList[order(sapply(oList, `[[`, i=1))] print(unlist(oList)) #default order (alphabetical or numerical depending on type) #sort a vector: oVec = c("a", "bb", "ccc", "d", "ee", "fff", "aa") #oVec = c(1, 22, 333, 4, 55, 666, 11) print(oVec) #unsorted oTemp = as.list(oVec) class(oTemp) = "MyClass" oVec = unlist(sort(oTemp)) print(oVec) #custom order (string length) oVec = sort(oVec) print(oVec) #default order (alphabetical or numerical depending on type)
temporary variables within one-liners: MySQL/PostgreSQL/SQLite: SELECT vTemp1+vTemp2+vTemp3 FROM (SELECT 1 AS vTemp1, 2 AS vTemp2, 3 AS vTemp3) oTemp MySQL/PostgreSQL/SQLite: SELECT oTemp.a+oTemp.b+oTemp.c FROM (SELECT 1 AS a, 2 AS b, 3 AS c) oTemp MySQL/PostgreSQL/SQLite: SELECT vTemp*2 FROM (SELECT 123 AS vTemp) oTemp PostgreSQL: SELECT vTemp*2 FROM coalesce(123) vTemp SQLite: SELECT vTemp1+vTemp2+vTemp3 FROM (SELECT 1 AS vTemp1, 2 AS vTemp2, 3 AS vTemp3) -- note: like the approach listed earlier, but without a table name SQLite: SELECT vTemp*2 FROM (SELECT 123 AS vTemp) -- note: like the approach listed earlier, but without a table name temporary variables within one-liners ('with' clause): MySQL: WITH oTemp (vNum1, vNum2) AS (VALUES row(123, 456)) SELECT * FROM oTemp; PostgreSQL/SQLite: WITH oTemp (vNum1, vNum2) AS (VALUES (123, 456)) SELECT * FROM oTemp; MySQL/PostgreSQL/SQLite: WITH oTemp (vNum1, vNum2) AS (SELECT 123, 456) SELECT * FROM oTemp; MySQL/PostgreSQL/SQLite: WITH oTemp AS (SELECT 123 AS vNum1, 456 AS vNum2) SELECT * FROM oTemp; temporary variables within one-liners ('with' clause), add values: MySQL/PostgreSQL/SQLite: WITH oTemp AS (SELECT 123 AS vNum1, 456 AS vNum2) SELECT vNum1+vNum2 FROM oTemp; MySQL/PostgreSQL/SQLite: WITH oTemp AS (SELECT 123 AS vNum1, 456 AS vNum2) SELECT (SELECT vNum1+vNum2 FROM oTemp); MySQL/PostgreSQL/SQLite: WITH oTemp AS (SELECT 123 AS vNum1, 456 AS vNum2) SELECT oTemp.vNum1+oTemp.vNum2 FROM oTemp; MySQL/PostgreSQL/SQLite: WITH oTemp AS (SELECT 123 AS vNum1, 456 AS vNum2) SELECT (SELECT vNum1 FROM oTemp)+(SELECT vNum2 FROM oTemp); temporary tables within one-liners (e.g. from a JSON array): MySQL/PostgreSQL/SQLite: use json_table()/unnest()/json_each() to create a temporary table: SQLite: use json_each() to create a temporary table which has a column called 'value': MySQL: SELECT vTemp*2 FROM json_table(CAST(json_array(1, 2, 3) AS CHAR), '$[*]' columns(vTemp INT PATH '$')) oTemp PostgreSQL: SELECT vTemp*2 FROM unnest(ARRAY[1, 2, 3]) vTemp SQLite: SELECT value*2 FROM json_each(json_array(1, 2, 3)) SQLite: SELECT value*2 FROM json_each(json_array(1, 2, 3)) oTemp SQLite: SELECT oTemp.value*2 FROM json_each(json_array(1, 2, 3)) oTemp SQLite: SELECT vTemp*2 FROM (SELECT value AS vTemp FROM json_each(json_array(1, 2, 3))) use aggregate functions like regular functions (e.g. sum): MySQL: SELECT sum(vTemp) FROM json_table(CAST(json_array(1, 2, 3, 4) AS CHAR), '$[*]' columns(vTemp INT PATH '$')) oTemp MySQL: SELECT sum(vTemp) FROM json_table(concat('[', concat_ws(',', 1, 2, 3, 4), ']'), '$[*]' columns(vTemp INT PATH '$')) oTemp PostgreSQL: SELECT sum(vTemp) FROM unnest(ARRAY[1, 2, 3, 4]) vTemp PostgreSQL: SELECT sum(vTemp) FROM json_table(json_array(1,2,3,4), '$[*]' columns(vTemp INT PATH '$')) oTemp PostgreSQL: SELECT sum(vTemp) FROM json_table('['||concat_ws(',', 1, 2, 3, 4)||']', '$[*]' columns(vTemp INT PATH '$')) oTemp SQLite: SELECT sum(value) FROM json_each(json_array(1, 2, 3, 4)) SQLite: SELECT sum(value) FROM json_each('['||concat_ws(',', 1, 2, 3, 4)||']') use concat_ws() to concatenate strings: MySQL/PostgreSQL/SQLite: SELECT concat_ws('|', 'a', '', 'b', NULL, 'c'); -- include blanks, omit nulls use aggregate functions to concatenate strings: MySQL: SELECT group_concat(vTemp SEPARATOR '|') FROM json_table(CAST(json_array('a', '', 'b', NULL, 'c') AS CHAR), '$[*]' columns(vTemp TEXT PATH '$')) oTemp; -- include blanks, omit nulls (equivalent to concat_ws()) MySQL: SELECT group_concat(vTemp SEPARATOR '|') FROM json_table(CAST(json_array('a', '', 'b', NULL, 'c') AS CHAR), '$[*]' columns(vTemp TEXT PATH '$')) oTemp WHERE vTemp != ''; -- omit blanks, omit nulls MySQL: SELECT group_concat(coalesce(vTemp, '') SEPARATOR '|') FROM json_table(CAST(json_array('a', '', 'b', NULL, 'c') AS CHAR), '$[*]' columns(vTemp TEXT PATH '$')) oTemp; -- include blanks, include nulls (as blanks) PostgreSQL: SELECT string_agg(vTemp, '|') FROM unnest(ARRAY['a', '', 'b', NULL, 'c']) vTemp; -- include blanks, omit nulls (equivalent to concat_ws()) PostgreSQL: SELECT string_agg(vTemp, '|') FROM unnest(ARRAY['a', '', 'b', NULL, 'c']) vTemp WHERE vTemp != ''; -- omit blanks, omit nulls PostgreSQL: SELECT string_agg(coalesce(vTemp, ''), '|') FROM unnest(ARRAY['a', '', 'b', NULL, 'c']) vTemp; -- include blanks, include nulls (as blanks) SQLite: SELECT group_concat(value, '|') FROM json_each(json_array('a', '', 'b', NULL, 'c')); -- include blanks, omit nulls (equivalent to concat_ws()) SQLite: SELECT group_concat(value, '|') FROM json_each(json_array('a', '', 'b', NULL, 'c')) WHERE value != ''; -- omit blanks, omit nulls SQLite: SELECT group_concat(coalesce(value, ''), '|') FROM json_each(json_array('a', '', 'b', NULL, 'c')); -- include blanks, include nulls (as blanks) use aggregate functions to sort table rows and concatenate (copied from Array.Join): SQL (MySQL): SELECT group_concat(v ORDER BY k SEPARATOR MySep) FROM MyTable SQL (MySQL): WARNING: does not sort: SELECT group_concat(v SEPARATOR '|') FROM MyTable ORDER BY k SQL (MySQL): WARNING: does not sort: SELECT group_concat(v SEPARATOR '|') FROM (SELECT v FROM MyTable ORDER BY k) oTemp SQL (PostgreSQL): SELECT string_agg(v, MySep ORDER BY k) FROM MyTable SQL (PostgreSQL): SELECT string_agg(v, MySep) FROM (SELECT v FROM MyTable ORDER BY k) oTemp SQL (SQLite): SELECT group_concat(v, MySep ORDER BY k) FROM MyTable SQL (SQLite): SELECT group_concat(v, MySep) FROM (SELECT v FROM MyTable ORDER BY k) SQL (SQLite): WARNING: does not sort: SELECT group_concat(v, MySep) FROM MyTable ORDER BY k combine 2 tables (e.g. generate 'A1|A2|A3, B1|B2|B3, C1|C2|C3'): MySQL: SELECT (SELECT group_concat(concat(vTemp1, vTemp2) SEPARATOR '|') FROM json_table(CAST(json_array(1,2,3) AS CHAR), '$[*]' columns(vTemp2 INT PATH '$')) oTemp2) FROM json_table(CAST(json_array('A','B','C') AS CHAR), '$[*]' columns(vTemp1 TEXT PATH '$')) oTemp1 MySQL: SELECT concat(vTemp1, vTemp2) FROM (json_table(CAST(json_array('A','B','C') AS CHAR), '$[*]' columns(vTemp1 TEXT PATH '$')) oTemp1 CROSS JOIN json_table(CAST(json_array(1,2,3) AS CHAR), '$[*]' columns(vTemp2 INT PATH '$')) oTemp2) ORDER BY concat(vTemp1, vTemp2) MySQL: SELECT concat(vTemp1, vTemp2) FROM (json_table(CAST(json_array('A','B','C') AS CHAR), '$[*]' columns(vID1 FOR ORDINALITY, vTemp1 TEXT PATH '$')) oTemp1 CROSS JOIN json_table(CAST(json_array(1,2,3) AS CHAR), '$[*]' columns(vID2 FOR ORDINALITY, vTemp2 INT PATH '$')) oTemp2) ORDER BY vID1, vID2 PostgreSQL: SELECT (SELECT string_agg(vTemp1||vTemp2, '|') FROM json_table(json_array(1,2,3), '$[*]' columns(vTemp2 INT PATH '$')) oTemp2) FROM json_table(json_array('A','B','C'), '$[*]' columns(vTemp1 TEXT PATH '$')) oTemp1 PostgreSQL: SELECT vTemp1||vTemp2 FROM (json_table(json_array('A','B','C'), '$[*]' columns(vTemp1 TEXT PATH '$')) oTemp1 CROSS JOIN json_table(json_array(1,2,3), '$[*]' columns(vTemp2 INT PATH '$')) oTemp2) SQLite: SELECT (SELECT group_concat(vTemp||value, '|') FROM json_each(json_array(1,2,3))) FROM (SELECT value as vTemp FROM json_each(json_array('A','B','C'))) SQLite: SELECT vTemp1||vTemp2 FROM (SELECT value AS vTemp1 FROM json_each(json_array('A','B','C'))) CROSS JOIN (SELECT value AS vTemp2 FROM json_each(json_array(1,2,3))) SQL Array.NewAnyDemo extra notes (store as string and type name): MySQL: CREATE TABLE MyTable (k INTEGER PRIMARY KEY AUTO_INCREMENT, v TEXT, t TEXT); INSERT INTO MyTable (v,t) VALUES ('abc','TEXT'), ('','TEXT'), ('-123','INT'), ('0','INT'), ('123','INT'), ('-123.456','DOUBLE'), ('-0.0','DOUBLE'), ('0.0','DOUBLE'), ('123.456','DOUBLE'), ('true','BOOL'), ('false','BOOL'), ('-Infinity','DOUBLE'), ('Infinity','DOUBLE'), ('NaN','DOUBLE'); SELECT * FROM MyTable; SELECT k,(CASE WHEN t='TEXT' THEN v ELSE NULL END) v FROM MyTable; SELECT k,(CASE WHEN t='INT' THEN CAST(v AS SIGNED) ELSE NULL END) v FROM MyTable; SELECT k,(CASE WHEN t!='DOUBLE' THEN NULL WHEN v='NaN' THEN NULL WHEN v='Infinity' THEN 1.7976931348623157E+308 WHEN v='-Infinity' THEN -1.7976931348623157E+308 ELSE CAST(v AS DOUBLE) END) v FROM MyTable; SELECT k,(CASE WHEN t='BOOL' THEN (lower(v) = 'true') ELSE NULL END) v FROM MyTable; PostgreSQL: CREATE TABLE MyTable (k SERIAL PRIMARY KEY, v TEXT, t TEXT); INSERT INTO MyTable (v,t) VALUES ('abc','TEXT'), ('','TEXT'), ('-123','INT'), ('0','INT'), ('123','INT'), ('-123.456','DOUBLE'), ('-0.0','DOUBLE'), ('0.0','DOUBLE'), ('123.456','DOUBLE'), ('true','BOOL'), ('false','BOOL'), ('-Infinity','DOUBLE'), ('Infinity','DOUBLE'), ('NaN','DOUBLE'); SELECT * FROM MyTable; SELECT k,(CASE WHEN t='TEXT' THEN v ELSE NULL END) FROM MyTable; SELECT k,(CASE WHEN t='INT' THEN v::int ELSE NULL END) FROM MyTable; SELECT k,(CASE WHEN t='DOUBLE' THEN v::float ELSE NULL END) FROM MyTable; SELECT k,(CASE WHEN t='BOOL' THEN v::bool ELSE NULL END) FROM MyTable; SQLite: .nullvalue NULL .mode table CREATE TABLE MyTable (k INTEGER PRIMARY KEY, v TEXT, t TEXT); INSERT INTO MyTable (v,t) VALUES ('abc','TEXT'), ('','TEXT'), ('-123','INT'), ('0','INT'), ('123','INT'), ('-123.456','DOUBLE'), ('-0.0','DOUBLE'), ('0.0','DOUBLE'), ('123.456','DOUBLE'), ('true','BOOL'), ('false','BOOL'), ('-Infinity','DOUBLE'), ('Infinity','DOUBLE'), ('NaN','DOUBLE'); SELECT * FROM MyTable; SELECT k,(CASE WHEN t=='TEXT' THEN v ELSE NULL END) FROM MyTable; SELECT k,(CASE WHEN t=='INT' THEN CAST(v AS INT) ELSE NULL END) FROM MyTable; SELECT k,(CASE WHEN t!='DOUBLE' THEN NULL WHEN v=='NaN' THEN NULL WHEN v=='Infinity' THEN 1e999 WHEN v=='-Infinity' THEN -1e999 ELSE CAST(v AS REAL) END) FROM MyTable; SELECT k,(CASE WHEN t=='BOOL' THEN (lower(v) == 'true') ELSE NULL END) FROM MyTable; generate series (e.g. 1 to 10): MySQL: SELECT vTemp FROM json_table(concat('[', repeat('0,', 10-1), '0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp; -- this algorithm returns 1 or more items MySQL: SELECT vTemp FROM json_table(concat('[', substr(repeat(',0', 10), 2), ']'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp; -- this algorithm returns 0 or more items MySQL: SELECT sum(vTemp) FROM json_table(concat('[', repeat('0,', 10-1), '0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp; PostgreSQL: SELECT generate_series(1, 10); PostgreSQL: SELECT sum(vTemp) FROM generate_series(1, 10) vTemp; SQLite: SELECT value FROM generate_series(1, 10); SQLite: SELECT sum(value) FROM generate_series(1, 10); SQLite: SELECT sum(vTemp) FROM (SELECT value AS vTemp FROM generate_series(1, 10)); SQLite: SELECT key+1 FROM json_each('['||replace(hex(zeroblob(10)), '00', '0,')||']'); generate series, reverse, concatenate (e.g. 1 to 10, as 10 to 1): PostgreSQL: SELECT string_agg(''||generate_series, ',') FROM (SELECT generate_series FROM generate_series(1, 10) ORDER BY generate_series DESC) oTemp; SQLite: SELECT group_concat(value ORDER BY value DESC) FROM generate_series(1, 10); SQLite: SELECT group_concat(value) FROM (SELECT value FROM generate_series(1, 10) ORDER BY value DESC); generate series (e.g. 5 to 100, step 5): MySQL: SELECT 5+(vTemp-1)*5 FROM json_table(concat('[', repeat('0,', floor(abs(100-5)/5)), '0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp; -- this algorithm returns 1 or more items MySQL: SELECT 5+(vTemp-1)*5 FROM json_table(concat('[', substr(repeat(',0', floor(abs(100-5)/5)+1), 2), ']'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp; -- this algorithm returns 0 or more items MySQL: SELECT sum(5+(vTemp-1)*5) FROM json_table(concat('[', repeat('0,', floor(abs(100-5)/5)), '0]'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp; PostgreSQL: SELECT generate_series(5, 100, 5); PostgreSQL: SELECT sum(vTemp) FROM generate_series(5, 100, 5) vTemp; SQLite: SELECT value FROM generate_series(5, 100, 5); SQLite: SELECT sum(value) FROM generate_series(5, 100, 5); SQLite: SELECT sum(vTemp) FROM (SELECT value AS vTemp FROM generate_series(5, 100, 5)); SQLite: SELECT 5+key*5 FROM json_each('['||replace(hex(zeroblob(1+abs(100-5)/5)), '00', '0,')||']'); generate series (using 'variable' names): MySQL: SET @vStart = 1; SET @vEnd = 10; SET @vStep = 1; SELECT @vStart+(vTemp-1)*@vStep FROM json_table(concat('[', substr(repeat(',0', floor(abs(@vEnd-@vStart)/@vStep)+1), 2), ']'), '$[*]' columns(vTemp FOR ORDINALITY)) oTemp; PostgreSQL: SELECT vTemp FROM (SELECT generate_series(vStart, vEnd, vStep) AS vTemp FROM (SELECT 1 AS vStart, 10 AS vEnd, 1 AS vStep) oTemp) vTemp; PostgreSQL: WITH oTemp AS (SELECT 1 AS vStart, 10 AS vEnd, 1 AS vStep) SELECT vTemp FROM generate_series((SELECT vStart FROM oTemp), (SELECT vEnd FROM oTemp), (SELECT vStep FROM oTemp)) vTemp; SQLite: WITH oTemp AS (SELECT 1 AS vStart, 10 AS vEnd, 1 AS vStep) SELECT value FROM generate_series((SELECT vStart FROM oTemp), (SELECT vEnd FROM oTemp), (SELECT vStep FROM oTemp)); see also: ForEachPrintDemo recursive CTE examples: SQLite: recursive CTE: cnt: The WITH Clause WITH RECURSIVE cnt(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM cnt WHERE x<1000000) SELECT x FROM cnt; SQLite: recursive CTE: generate_series: The generate_series Table-Valued Function WITH RECURSIVE generate_series(value) AS ( SELECT 5 UNION ALL SELECT value+5 FROM generate_series WHERE value+5<=100 ) SELECT value FROM generate_series; SQLite: recursive CTE: generate_series (adapted): WITH RECURSIVE MyGenerateSeries(vValue, vEnd, vStep) AS ( VALUES (5, 100, 5) UNION ALL SELECT vValue+vStep,vEnd,vStep FROM MyGenerateSeries WHERE vValue+vStep<=vEnd ) SELECT vValue FROM MyGenerateSeries;
[SQL][settings and printing (prettify) options] [SQL (SQLite)] [SQL (MySQL)] [SQL (PostgreSQL)] prettify: unique settings: PostgreSQL only: notifications e.g. CREATE/INSERT [remove notifications: \set QUIET 1] footers i.e. row counts [remove footers: \pset footer 0] SQLite only: .mode column: shows header row, adds header divider, adds spaces i.e. column alignment, doesn't add column dividers (pipes), doesn't add 4 border lines, (replaces pipes with spaces) [note: can turn off headers afterwards] .mode line: spreads all information vertically, one column only .mode box: shows header row, adds header divider, adds column alignment, adds column dividers (pipes), does add 4 border lines, (uses spaces and pipes), uses 11 Unicode characters to draw lines, (no blank lines between tables) [*can't* turn off headers afterwards] .mode table: shows header row, adds header divider, adds column alignment, adds column dividers (pipes), does add 4 border lines, (uses spaces and pipes), uses 3 ASCII characters to draw lines, (no blank lines between tables) [*can't* turn off headers afterwards] .separator "|" "\n": e.g. to double up column/row separators: .separator "||" "\n\n" .width 10 3 30 [e.g. column 1 width 10, column 2 width 3, column 3 width 30] prettify: settings: SQLite: true/false as 1/0 MySQL: true/false as 1/0 PostgreSQL: true/false as t/f [print true/false as true/false workaround: SELECT MyCol1,MyCol2,CASE when MyCol3=TRUE THEN 'true' else 'false' END AS MyCol3Mod FROM MyTable] SQLite: null as (blank) [change display for null: .nullvalue NULL] MySQL: null as NULL PostgreSQL: null as (blank) [change display for null: \pset null NULL] SQLite: no header row [show header rows: .headers on] [note: some modes disallow .headers off] MySQL: header row PostgreSQL: header row [removes header rows (and footers i.e. row counts): \pset tuples_only] SQLite: no column alignment MySQL: column alignment PostgreSQL: column alignment SQLite: no borders (top/bottom/sides) [add borders (and other things): .mode table] [Unicode borders: .mode box] MySQL: borders (top/bottom/sides) PostgreSQL: no borders [add borders: \pset border 2] [Unicode borders: \pset linestyle unicode] SQLite: doesn't print blank lines between tables MySQL: doesn't print blank lines between tables PostgreSQL: prints blank lines between tables [remove blank lines (but also column alignment): \a] prettify: further notes: SQLite: one-off print blank line: [SELECT ''] [note: doesn't work when various .mode options are set, a table would be drawn] MySQL: PostgreSQL: SQLite: when values (e.g. int/string) printed, header row is value MySQL: when values (e.g. int/string) printed, header row is value PostgreSQL: when values (e.g. int/string) printed, header row is '?column?' prettify: mimic other SQL variants: SQLite: mimic MySQL: .mode table, .nullvalue NULL [e.g. differences: spaces per column, left/centre/right column alignment, column names for values] mimic PostgreSQL: .mode column [e.g. differences: left/centre/right column alignment, column names for values, no column dividers (pipes), no blank lines between items, true/false values] PostgreSQL: mimic MySQL: \set QUIET 1, \pset footer 0, \pset border 2, \pset null NULL [e.g. differences: spaces per column, left/centre/right column alignment, column names for values, has blank lines between items, true/false values] mimic SQLite: \set QUIET 1, \pset tuples_only, \pset border 0, \a [e.g. differences: true/false values] general: list built-in variables: MySQL: list built-in variables: SHOW VARIABLES; SHOW VARIABLES LIKE 'a%'; SHOW VARIABLES WHERE Variable_name REGEXP '^[a-n]'; SHOW VARIABLES WHERE Variable_name REGEXP '^[o]'; SHOW VARIABLES WHERE Variable_name REGEXP '^[p-u]'; SHOW VARIABLES WHERE Variable_name REGEXP '^[v-z]'; SHOW VARIABLES WHERE Variable_name REGEXP '^[^b-z]'; SHOW VARIABLES WHERE Variable_name = 'sql_mode'; SHOW VARIABLES LIKE '%collat%'; -- e.g. 'utf8mb4_0900_ai_ci' SHOW VARIABLES LIKE '%char%'; -- e.g. 'utf8mb4', 'binary' SHOW VARIABLES WHERE Value LIKE '%utf%'; PostgreSQL: list built-in variables: SELECT COUNT(*) FROM pg_settings; SELECT * FROM pg_settings WHERE regexp_like(name, '^a'); SELECT * FROM pg_settings WHERE regexp_like(name, '^[^b-z]'); SELECT * FROM pg_settings WHERE name = 'max_function_args'; SELECT pg_client_encoding(); -- e.g. 'UTF8' general: print version number: SQLite: SELECT sqlite_version(); SQLite: .version MySQL: SELECT version(); PostgreSQL: SELECT version(); general: maximum function arguments (and maximum expression depth): SQLite: [SQLITE_MAX_FUNCTION_ARG: default e.g. v3.27.2: 127, v3.48.0+: 1000] [SQLITE_MAX_EXPR_DEPTH: default: 1000] SQLite: .limit function_arg SQLite: .limit expr_depth PostgreSQL: ['determined by the value of FUNC_MAX_ARGS'] SELECT * FROM pg_settings WHERE name = 'max_function_args'; general: further: MySQL: set || as a concat operator (rather than a logical OR operator): set sql_mode=PIPES_AS_CONCAT; PostgreSQL: '\' handling: from PostgreSQL 9.1 onwards, 'standard_conforming_strings' is set to on, i.e. '\' is treated literally, use the 'E' prefix, e.g. E'\n', to use '\' as an escape char, to get this value: SELECT setting FROM pg_settings WHERE name = 'standard_conforming_strings'; to set this value to on: SET standard_conforming_strings = on; to set this value to off (not recommended): SET standard_conforming_strings = off;
[Java function objects] When you create a function object (lambda function) (anonymous function) in Java... Unlike in almost all programming languages... You have to give the function object a special type. E.g. ToIntFunction<Integer> MyDouble = vNum -> vNum*2 E.g. see the examples for map/reduce/filter. And unlike in almost all programming languages... You can't just call the function object directly, you have to call its method. E.g. MyDouble.applyAsInt(vNum) Also, to create certain kinds of function objects, such as one that accepts 3 parameters... You may need to create a custom interface. E.g. see MyTriFunction below. To summarise Java function types and methods: Consumer objects: accept. Function/Operator objects: apply or applyAsXXX. Predicate objects: test. Supplier objects: get or getAsXXX. A list of Java function types and methods: Based on: java.util.function (Java Platform SE 8 )
T,U,v BiConsumer<T,U> accept T,U,R BiFunction<T,U,R> apply T,T,T BinaryOperator<T> apply T,U,b BiPredicate<T,U> test b BooleanSupplier getAsBoolean T,v Consumer<T> accept d,d,d DoubleBinaryOperator applyAsDouble d,v DoubleConsumer accept d,R DoubleFunction<R> apply d,b DoublePredicate test d DoubleSupplier getAsDouble d,i DoubleToIntFunction applyAsInt d,l DoubleToLongFunction applyAsLong d,d DoubleUnaryOperator applyAsDouble T,R Function<T,R> apply i,i,i IntBinaryOperator applyAsInt i,v IntConsumer accept i,R IntFunction<R> apply i,b IntPredicate test i IntSupplier getAsInt i,d IntToDoubleFunction applyAsDouble i,l IntToLongFunction applyAsLong i,i IntUnaryOperator applyAsInt l,l,l LongBinaryOperator applyAsLong l,v LongConsumer accept l,R LongFunction<R> apply l,b LongPredicate test l LongSupplier getAsLong l,d LongToDoubleFunction applyAsDouble l,i LongToIntFunction applyAsInt l,l LongUnaryOperator applyAsLong o,d,v ObjDoubleConsumer<T> accept o,i,v ObjIntConsumer<T> accept o,l,v ObjLongConsumer<T> accept T,b Predicate<T> test T Supplier<T> get T,U,d ToDoubleBiFunction<T,U> applyAsDouble T,d ToDoubleFunction<T> applyAsDouble T,U,i ToIntBiFunction<T,U> applyAsInt T,i ToIntFunction<T> applyAsInt T,U,l ToLongBiFunction<T,U> applyAsLong T,l ToLongFunction<T> applyAsLong T,T UnaryOperator<T> apply The most general of the function types above that don't return a value: T,v Consumer<T> accept T,U,v BiConsumer<T,U> accept The most general of the function types above that do return a value: T Supplier<T> get T,R Function<T,R> apply T,U,R BiFunction<T,U,R> apply
Here's code for a custom interface, to create anonymous functions that take 3 parameters:
//place import and custom interface at the top: import java.util.function.*; @FunctionalInterface interface MyTriFunction<A,B,C,R> { R apply(A a, B b, C c); } //define and call anonymous function in the body: MyTriFunction<Integer,Integer,Integer,Integer> MyAdd3 = (vNum1, vNum2, vNum3) -> vNum1 + vNum2 + vNum3; System.out.println(MyAdd3.apply(1,2,3)); //6