fabiochiu/medium-articles huggingface dataset:
The Ruby Array Map Method with examples
By: Akhilesh Sharma
Tags: Ruby On Rails Development, Array Methods, Ruby, Rails, Array

Hi folks, we use arrays as a data structure in almost all languages. Small arrays are very easy to create,destroy and can be very easily used to transform and manipulate data with single liners with no hassle of having to code complete implementations for memory management.(Arrays can be pretty complex too)

Now to modify the values of an array many languages use a very familiar method Map. Some of the earliest use of Map is with functional programming languages like Lisp(maplist). The concept of a map is not limited to lists or arrays ,however it works for abstract containers such as futures and promises(javascript) or with hashes(ruby).

In ruby map method takes an enumerable object( to be iterated upon) and a code block(ruby code block syntax {} or begin end), and runs the block for each element, adds the result of each iteration to a new array.

Taking some examples of use of map in ruby

The basic concept is take elements one by one send it to the code block(chunk of code), where one can modify data(like called add one in the example above) and let that method return some value for each element and add it to another array which is returned after all the iterations.

This covers the very basic use of arrays in Ruby.

Btw if you want to check the C code for map

From: array.c (C Method): Owner: Array Visibility: public Number of lines: 13 static VALUE rb_ary_collect(VALUE ary) { long i; VALUE collect; RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length); collect = rb_ary_new2(RARRAY_LEN(ary)); for (i = 0; i < RARRAY_LEN(ary); i++) { rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i))); } return collect; }

If you have used the map method in other languages as well or want to use it below is a link you can refer to, for easy links to documentation in python,ruby and javascript.

http://www.spors.in/users/akhileshsharma.akisTV/properties/5cdd7d5d0093250022475757
Difference between Arrays and JSON Objects
By: Angela Amarapala
Tags: JavaScript, Arrays, Objects, Typescript, Angular

Designed by Freshgraphix / Freepik

Sometimes most of us get confused while dealing with Arrays and Objects. This leads into further confusions when choosing which manipulation technique to use. For example, we can find the length only if we know whether it is an array or an object. As both have different approaches.

This is a basic checklist for all the programmers coding out there. So, in this blog you will learn how to differentiate between Arrays and Objects.

What are Arrays?

Array items are accessed using indices

Format [ , , , ]

Example [1, 2, 3, 4, 5]

Arrays can contain objects, strings, numbers, arrays & boolean.

Initialization

1. datatype[] = [ , , , ]; 2. Array<datatype> = [ , , , ]; // Uses a generic array type

Array of objects

Syntax :

[{“ “:” “,” “:” “},{“ “:” “,” “:” “}]

Example:

[

{ “position”: “winner”,”country”: “U.S.A” }, { “position”: “runner”,”country”: “China” } ]; [

{ “rainy”: true,”sunny”: false }, { “rainy”: false,”sunny”: true } ]

Array of strings

Example:

[‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,’Friday’, ‘Saturday’]; [‘a’, ‘b’, ‘c’, ‘d’]; [‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ’6’, ‘7’];

Array of numbers

Example:

[1, 2, 3, 4, 5]; [788.34, 432.34, 3234.72];

Array of arrays

These can be otherwise called as multi-dimensional arrays.

[ [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7] ];

Array of booleans

[true, false, false, true]

What are Objects?

An object is a collection of properties, and a property is an association between a name (or key) and a value. A property’s value can be a function, in which case the property is known as a method.

Object properties are accessed using keys.

Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).

Format { “ ”: “ ” }

Example {“position”: “winner”,”country”: “U.S.A”}

Object of arrays and objects

{ “binary”: [{“id”:1,”name”:0},{“id”:2,”name”:1}], “boolean”: [{“id”:1,”value”: false},{“id”:2,”value”: true}] }

Nested Objects:

“results”: { “tennis”: [

{“position”: “winner”,“country”: “U.S.A}, {“position”: “runner”,“country”: “China”}

] }

Object of objects

JSON Objects are enclosed within {}

“universe”: { “planets”: { “day”: “Sun”, “night”: “Moon” } }

Nested JSON Object:

json: any = { "visible": true, "colors": { "data": { "darkest": "Black", "lightest": "white", "neutral": "Grey", "spectrum": { "1": "Violet", "2": "Indigo", "3": "Blue", "4": "Green", "5": "Yellow", "6": "Orange", "7": "Red" }, "default": "Grey", "primary": "Blue", "danger": "Red", "warning": "Yellow", "success": "Green", "RGB": { "r": "Red", "g": "Green", "b": "Blue" } } } }

So these are the differences between Arrays and Objects. I hope that from now you all can use these types without any worries.

Happy coding :)
Connecting the dots — Big O and Array Data Structure
By: Deepa Subramanian
Tags: Data Structures, Beginner, Arrays, Big O Notation

In my previous article, I mentioned that algorithms are steps performed on some data to solve some problem(s). Data structures are ways we structure, manage and organize data. For example, If you want to sort the videos in YouTube, we click the sort icon to sort. How does it sort? There are data structures available for sorting.

Types of Data Structures

There are many data structures such as Arrays, LinkedList, Binary search tree, Stack, Queue, Graph etc and some of these names are language specific. For example, in Java we call it as Hash table and in JavaScript it is referred as Objects (I will be using with JavaScript here). We determine which data structure is better at certain situation using Big O.

Data Structures

Let us see the correlation of Big O and the Array data structure. An Array is a collection of items. It could be strings, numbers or combination of both. We can add or remove items to an array. The efficiency of an algorithm changes based on the where you add or remove items in an array. You can insert or delete elements from the beginning, middle or at the end.

Beginning :

In the below diagram, there is an array of items listed where we are trying to add an item at the beginning. When we add an array, we shift() the rest of the items and all the indices corresponding to the array needs reindexing. The same applies with removing an item [unshift()]at the beginning of the array. Recollect what is Big O(n)? The time taken for this operation is proportional to the size of the array. So, it takes linear time to add or remove an element at the beginning.

Beginning of the Array

Middle:

To add an item in the middle of the array we use splice(). When we insert an item in the middle, the rest of the items needs reindexing. This is similar to adding array at the beginning of the array. Therefore, this operation will also be in linear time or Big O(n).

Middle of the Array

End:

When we perform a push() or pop() items on an array at the end, we do not need to reindex. In this case, the time taken for this operation is constant to the size of the array. So, it takes Big O(1) or constant time to add or remove an element at the end. Easy?

End of the Array

To summarize, Array will have time complexities of Big O(n) or Big O(1) depending on where insertion and deletion of items takes place and the space complexity will be Big O(n). In the next article, we will see another data structure with Big O notation.

If you like this article please follow and give me a clap!

Resources:

MDN , Grokking Algorithms
How to convert a PDF to PNG array in Ruby
Tags: Png, Ruby, Convert, Pdf, Arrays

Converting a PDF file to a PNG array is incredibly simple if you apply our conversion API. First step, add this to your Gemfile to access our API client.

gem 'cloudmersive-convert-api-client', '~> 1.3.3'

Now just call the convert_document_pdf_to_png_array function:

# load the gem

require 'cloudmersive-convert-api-client'

# setup authorization

CloudmersiveConvertApiClient.configure do |config|

# Configure API key authorization: Apikey

config.api_key['Apikey'] = 'YOUR API KEY'

# Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)

#config.api_key_prefix['Apikey'] = 'Bearer'

end api_instance = CloudmersiveConvertApiClient::ConvertDocumentApi.new input_file = File.new("/path/to/file") # File | Input file to perform the operation on. begin

#PDF to PNG Array

result = api_instance.convert_document_pdf_to_png_array(input_file)

p result

rescue CloudmersiveConvertApiClient::ApiError => e

puts "Exception when calling ConvertDocumentApi->convert_document_pdf_to_png_array: #{e}"

end

And you’re done! You will get back a JSON file that contains URLs for each PNG, which can then be viewed or downloaded at your leisure. APIs sure make things easy, huh?
LeetCode — Defuse the Bomb
By: Steven Lu
Tags: Leetcode, Arrays

You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k .

To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.

If k > 0 , replace the ith number with the sum of the next k numbers.

, replace the number with the sum of the next numbers. If k < 0 , replace the ith number with the sum of the previous k numbers.

, replace the number with the sum of the previous numbers. If k == 0 , replace the ith number with 0 .

As code is circular, the next element of code[n-1] is code[0] , and the previous element of code[0] is code[n-1] .

Given the circular array code and an integer key k , return the decrypted code to defuse the bomb!

Example 1:

Input: code = [5,7,1,4], k = 3

Output: [12,10,16,13]

Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.

Example 2:

Input: code = [1,2,3,4], k = 0

Output: [0,0,0,0]

Explanation: When k is zero, the numbers are replaced by 0.

Example 3:

Input: code = [2,4,9,3], k = -2

Output: [12,5,6,13]

Explanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers.

Constraints:
Spring JPA/Data with Postgres UUID Array Types
By: Sergii Chub
Tags: Spring Boot, Uuid, Postgresql, Arrays, Spring Data

We had a very typical situation when we need to hold an array of UUID’s in a Postgres table. That can be solved by two ways:

install `hibernate-types` library to your project

create custom `UserType`

In our projects we can’t third party library. So let create `GenericUuidArrayUserType` class

public class GenericUuidArrayUserType<T extends Serializable> implements UserType {

protected static final int[] SQL_TYPES = {Types.ARRAY};

private Class<T> typeParameterClass;



@Override

public Object assemble(Serializable cached, Object owner) throws HibernateException {

return this.deepCopy(cached);

}



@Override

public Object deepCopy(Object value) throws HibernateException {

return value;

}



@SuppressWarnings("unchecked")

@Override

public Serializable disassemble(Object value) throws HibernateException {

return (T) this.deepCopy(value);

}



@Override

public boolean equals(Object x, Object y) throws HibernateException {



if (x == null) {

return y == null;

}

return x.equals(y);

}



@Override

public int hashCode(Object x) throws HibernateException {

return x.hashCode();

}



@Override

public Object nullSafeGet(ResultSet resultSet, String[] names,

SharedSessionContractImplementor sharedSessionContractImplementor, Object o)

throws HibernateException, SQLException {

Array array = resultSet.getArray(names[0]);

if (array == null) {

return null;

}

if (resultSet.getArray(names[0]) == null) {

return new UUID[0];

}



@SuppressWarnings("unchecked")

T javaArray = (T) array.getArray();

return javaArray;

}



@Override

public void nullSafeSet(PreparedStatement statement, Object value, int index,

SharedSessionContractImplementor sharedSessionContractImplementor)

throws HibernateException, SQLException {

Connection connection = statement.getConnection();

if (value == null) {

statement.setNull(index, SQL_TYPES[0]);

} else {

@SuppressWarnings("unchecked")

T castObject = (T) value;

Array array = connection.createArrayOf("uuid", (Object[]) castObject);

statement.setArray(index, array);

}

}



@Override

public boolean isMutable() {

return true;

}



@Override

public Object replace(Object original, Object target, Object owner) throws HibernateException {

return original;

}



@Override

public Class<T> returnedClass() {

return typeParameterClass;

}



@Override

public int[] sqlTypes() {

return new int[]{Types.ARRAY};

}

}

No we can use in our Entity

@Nullable

@Type(type = "my.app.demo.util.GenericUuidArrayUserType")

@Column(

name = "my_uuids_column",

columnDefinition = "uuid[]"

)

UUID[] myUuidsCoulmn;

Source link
Array Indexing / Slicing vs. Loops
By: Jason Eden
Tags: Python, Indexing, Arrays, Numpy

A Simple, Straightforward Example of a Powerful Concept

Just a quick write-up (you’ll be relieved to learn there are no jokes in this one. Except this one.) In the Cornell data science courses I have taken so far, they have heavily emphasized the need to use indexing and slicing instead of loops, especially when working with large data sets. The reason is speed: doing an iterative loop to perform some kind of matrix math is dramatically slower in python than the alternative. It also turns out to be easier to code and understand, once you get a grasp on the concepts.

The problem is that most of us were taught that loops were the end-all, be-all of application development, we know how to write them, and they work, so it’s easy to want to use them. Let’s take a look at an example:

A really simple example to start with

Let’s say we want to find the sum of all of the rows that have a label of 1, and the product of rows that have a label of 0. You could write a loop to accomplish this, but that would turn out to be a fair amount of code for a pretty easy operation, and on a really large data set, would take a fair amount of time. What if, instead, we started by subsetting our data by label, and then applying the operations we want to run on the appropriate subsets only?

First, let’s look at how we would create those subsets:

Proof of concept

We created a separate matrix that contains only the data that had a label of 1. Note that any valid logical operator would work here: “>”, “<”, and so forth.

Now that we know how to conceptually create the subset, start the operation by creating the variable where you want to store your output. We have four observations/labels, so our output should be shaped accordingly:

A place to write values

Now, let’s put everything together that we’ve learned so far and populate our datastuff variable with the sums out of our data variable where the label = 1.

No loops required!

You would then repeat the operation, only replace labels==1 with labels==0, and np.sum with np.prod. If you want to take a look at the code from beginning to end, as well as the final outputs, you can check it out here.
Find first three largest elements in a given array
By: Tutorial Horizon
Tags: Algorithms, Programming, Arrays

Objective: Given an array of integers, write an algorithm to find the first three largest elements in the array.

Example:

Int [] a = { 6, 8, 1, 9, 2, 1, 10}; Output: 10, 9, 8 Int [] a = { 6, 8, 1, 9, 2, 1, 10, 10}; Output: 10, 10, 9 Int [] a = {6}; Output: Invalid Input, array size is less than 3

Approach:

Take three variables; let’s call them first, second and third and mark them as -∞. Iterate through the array and for each element (let’s call it current), Compare it with the first and if first is less, assign the first value to second and second value to third and assign current to first. If above step is not true then current element might be a candidate of second highest element, so check if current>second, if yes then assign second value to third and assign current to second. If above step is not true then current element might be a candidate of third highest element, so check if current>third, if yes then assign current to third.

See the code below for more understanding.

Code:

Output:
Using Flat Method in javascript
By: Ishan Vimukthi
Tags: Array Methods, JavaScript, ES6, Arrays, Code

Flat earth

If you’re into programming you must know about arrays and work with them. Have u ever came through this type of problem?

Eg :- [1,[2,[3,[4]]]]

and tried to flatten it like this

[1,2,3,4]

🤔🤔🤔🤔 ?

If the answer is yes then u know the troubles you had and u may have used recursion to resolve every nested level and flatten the array but javascript has introduced a method called flat() for arrays “Array.prototype.flat()” and it makes your life easier.

By using a flat method u can easily flatten the array up to a specified depth using flat(depthAsANumber) and you can call flat() without arguments if u want to flatten one level.

code

______

[1,[2,[3,[4]]]].flat(3)

output

_______

[1, 2, 3, 4]

but what happens if u cant count the nested levels and an array is nested deeper 😬😬😬😬?

don’t worry we can call flat() using javascript “Infinity-a numeric value representing infinity” like this flat(Infinity).

so it flattens the array for any levels.

code

______

[1,[2,[3,[4]]],1,[2,[3,[4]]],1,[2,[3,[4]]],1,[2,[3,[4,1,[2,[3,[4]]]]]],1,[2,[3,[4]]]].flat(Infinity)

output

_______

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Flatten an array in Javascript without any inbuilt functions
By: Yogesh Nogia
Tags: Es 2019, Arrays, JavaScript

As of 2020, we have ES2019 which introduced a great method called flat () to deal with nested arrays and get the flattened array. The flat() method accepts a single parameter <depth>.

The depth defines the layers in the array. By default, it`s 1.

const oneLevel = [ '🔥', ['🦁', '🍕'], '🦋' ];

console.log( oneLevel.flat() ); //depth: 1

// ['🔥', '🦁', '🍕', '🦋']; const twoLevel = ['🔥', [ '🦁', ['👸', '🤴'], ' 🦋' ], '🍉']; console.log( twoLevel.flat() ); // depth: 1

['🔥', '🦁', ['👸', '🤴'], ' 🦋', '🍉'] console.log( twoLevel.flat(2) ); // depth: 2

// ['🔥', '🦁', '👸', '🤴', ' 🦋', '🍉']

Infinite Nested Arrays using flat()

const infiniteDeep = [...[], [..[..[[]..]..]..]]

infiniteDeep.flat(Infinity);

But, flat is a super new feature in the world of Javascript so all browser support is not there. Therefore, we calculate this using raw way

Infinite Nested Arrays without flat()

function flatArray(arr) { let result = []; // In this we`ll save the output; let main = arr, first; while(main.length > 0) { //1. Looping it first = main[0]; if(Array.isArray(first)) { Array.prototype.splice.apply(main, [0, 1].concat(first)); } else { result.push(first); main.splice(0, 1); } } return result; } console.log(flatArray(arr)); // Flatten array [.........]

There you go. A simple yet useful function in the world of javascript. Hope this was helpful.
Defining Fields of Type SET Within OpenAPI/Swagger
By: Nick Poulos
Tags: Api Design, API, Arrays, Swagger, Open Api

During a recent API design session, I came across a data type that should have taken three seconds to define, but ended up causing a little head scratching. And that task is — defining a SET data type within your Open API spec.

Seems easy enough right? And it is of course…but after several unhelpful Google queries later I still couldn’t quite get it right.

Now, I do realize I could have just made a new type or object specifically for this little data set.

/path/to/my/api:

get:

summary: My Custom API

description: |

Gets a List of FooBar IDs

produces:

- application/json

tags:

- FooBar

responses:

"200":

description: successful operation

schema:

$ref: "#/definitions/MyCustomType"

...

MyCustomType:

type: object

properties:

myCustomObject

type: ??? # list of string?

But that seemed like total overkill for what I needed, very verbose, and the data within would not quite live up to the name ‘object’. There just had to be a better way, right?? :).

For those who need a refresher, a `SET` is a kind of obscure little field type, found in MySQL, that is essentially an array of ENUM values. Say we have a SET field called “social_type”, with possible values of facebook twitter, instagram . That means “social_type” could a single value, like just facebook or twitter , just like your typical ENUM. However it could also be set to facebook, twitter or twitter, instagram or even all 3, facebook, twitter, instagram. So a SET holds one or more possible ENUM values, or an ARRAY of enums. And that is exactly how we should define it in our spec.

share_type:

type: array

enum:

- facebook

- pinterest

- tumblr

- twitter

- linkedin

uniqueItems: true

items: {}

I should point out the necessary uniqueItems flag that was set to TRUE here, as a SET cannot have a repeated value.

Super easy. Hopefully it saved somebody a few min Googling, thanks for reading.
7 ways to remove duplicates from an array in JavaScript
By: Jayanth Babu
Tags: Technology, Remove Duplicates, JavaScript, Programming Languages, Arrays

Photo by Skye Studios on Unsplash

It’s a common use case in many projects to need to remove duplicates from an array in JavaScript. For interviews, it’s a common coding challenge to practice for everyone.

Here are seven ways to filter out duplicates from an array and return only the unique values.

Use the filter Method

The filter method creates a new array of elements that pass the conditional we provide. And any element that fails or returns false , it will not be in the filtered array.

Remove duplicate elements from an array in JavaScript

And we can also use the filter method to retrieve the duplicate values from the array by simply adjusting our condition

By Using a Set

Sets are a new object type with ES6 (ES2015) that allows you to create collections of unique values.

Using the forEach Method

By using forEach , we can iterate over the elements in the array, and we will push into the new array if it doesn’t exist in the array.

By Using the reduce Method

Reduce is always a bit more tricky to understand. The reduce method is used to reduce the elements of the array and combine them into a final array based on some reducer function that you pass.

The same reduce method with a different approach

Adding a unique Method to the Array Prototype

In Javascript the array prototype constructor allows you to add new properties and methods to the Array object.

Sets will work much faster when you compare with the normal approach.

By Using Underscore JS

_.uniq method produces a duplicate-free version of the array, and also we can sort this array by passing the second parameter is true.

Removing Duplicate Objects from a Given Array

Some times it's a requirement to remove duplicate objects from an array of objects by the property name. We can achieve this by:

That's all! I hope this article might be helpful to delete duplicates from an array.

Thanks for reading :)
Array — Data Structure and Some Common Coding Problems
By: Chakresh Tiwari
Tags: LinkedIn, JavaScript, Java, Arrays, Data Structures

Photo by Pierre Bamin on Unsplash

An array is a linear data structure that is used for holding the same type of values. This is the common def. of the array.

But in actual when we should use array, whenever we want to hold some data of the same type either it is primitive or non-primitive we should use an array.

Like in our mobile phone we have contact lists that are also an array.

While using arrays there are some advantages and disadvantages also there-

Declaration:

For creating an array in different languages different syntaxes are there In this tutorial I will show you how to create an array using Java.

Initialize an array of size 10.

int[] array = new int[10];

2. If you want to create an array with some values.

int[] array = {1,2, 3,4,5};

You can iterate an array using a loop.

Advantages:

An array is index-based so it takes constant time to return an element.

e.g. If we want to get the element at index 4 then direct we can do

int element = arr[4];

It takes constant time in accessing data. But insert and delete operations are costly in an array.

Disadvantages:

In an array we can not store different kinds of values It will store only the same data type of values at a time. Array size is fixed.

So to overcome these problems of array new data structure came into the picture which is known as LinkedList. (Next post)

Some Common coding interviews Problems related to array:

1. Reverse an array.

2. Sum of array elements.

3. Find maximum and minimum elements of an array.

4. Search an element in an array.

5. Find the kth max and min element in an array.

6. Sort array of 0, 1, 2. with and without extra space.

7. Rotate array by one.

8. Find missing numbers from an array.

9. Move all negative numbers to one side of the array.

10. Union and Intersection of two arrays

11. Longest consecutive subsequence in an array.

These are some common problems and for the solution of these problems You can check out my Github and if you want a detailed explanation, or you want to learn more about complete DSA and Backend Development then connect with me on Linkedin

Hope you understood the basics of array Data structure. If any doubt or query reach out to me.

Thanks for reading!
Sock Merchant
By: Aman Lalpuria
Tags: Arrays, JavaScript, Nodejs

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are n=7 socks with colors ar=[1,2,1,2,1,3,2] . There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .

Functional Description

It must return an integer representing the number of matching pairs of socks that are available.

Sock Merchant has the following parameter(s):

n: the number of socks in the pile

ar: the colors of each sock

Output Format

Return the total number of matching pairs of socks that John can sell.

Sample Input

9

10 20 20 10 10 30 50 10 20

Sample Output

3

What I Tried !!!

function sockMerchant(n, ar) {

let countval = 0, val = 0, output=0

for (let i = 0; i < n; i++){

val = ar[i]

for (let j = i + 1; j < n; j++){

if (ar[j] == val)

{

countval++

}

}

let odd = countval % 2

console.log("odd" + odd)

countval = 0

output +=odd

}

console.log("output" + output)

return output

}

For the whole code, you can refer to — https://github.com/aman7797/NodeJs/blob/master/Sock%20Merchant.js
Array.prototype.filter() Woes
By: Pranavan Maru
Tags: Nested, Filters, Arrays, JavaScript

As far as non-lodash vanilla JS array methods go, filter() is the one I fancy the most as it gives you a reference to the array element making it possible to perform mutations on it. MDN Doc for the method lists few useful hacks the method can equip your code with in detail. However, when used with no caution, could lead to a popular pitfall with respect to nested arrays.

Walk in My Shoes 🚶

I had an array of objects, which I was filtering to find which of the elements had a particular property.

> [{a: "alpha", b: "bravo"},{a: "ammataudu"}].filter(el => el.b)

Works perfectly good. Finds me the one with property “b” in the object. Cut to Chase > Several sprints down, someone had a bright idea to construct a meta object and stack the data above within the meta object to solve a different problem. Reality of the world. You’ve got to play along with everybody. Point to note > Now my alphabet array is split and stacked inside an outer array.

meta alphabet object snapshot

Array.prototype.filter() gives you a reference to the object in the array for array of objects. which was the primary reason I had chosen to use it as I needed to mutate an incoming payload. (Worst thing to do, yet situation demanded it)

Now in the same spirit if I attempted to filter out the meta object that has my alphabet object with property “b” using 👇

> meta.filter(arr => arr.alphabet.filter(el => el.b))

You’ll get both the meta objects back.

First object has property b and returns true and is therefore added to the resultant array. Second object on the other hand has no reason to qualify, yet does.

Why 🤔

Reason for this is hidden at the very bottom of the documentation linked above. In the context of the inner array “alphabet”, filter takes each element through el => el.b to determine if it is a qualifier.

el.b evaluates to [{ a: ‘alpha’, b: ‘bravo’}] when run against the first alphabet array.

el.b evaluates to [] when run against the second alphabet array.

On the outer array’s filter method, these two functions evaluate to true when passed through lines 14–16 here. Making both elements of the meta array eligible for the final resultant array. This is the dry run explanation for the behavior disputed above.

Replacing the inner filter call with some or find Array.prototype methods, the desired output can be achieved.
Increasing triplet subsequence problem
By: Xiao Mei
Tags: Algorithms, Programming, Dynamic Programming, Arrays, Data Structures

Hi today, I have solved an algorithm issue (Increasing triplet subsequence) which is very interesting, I would like to share the solution.

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. Formally the function should: Return true if there exists i, j, k

such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.

Example 1:

Input: [1,2,3,4,5]

Output: true

Example 2:

Input: [5,4,3,2,1]

Output: false

So the purpose is to check if there exists a sub-sequential 3 integers (a, b, c) who increases which means a < b < c in the array.

Taking the note into consideration, the algorithm should run in O(n) time and O(1) space.

Thus my thought is that

We define a minimal first element minOne which indicates the minimal element which is the 1st of the triplet.

And we defined a minimal second element minTwo which indicates the minimal element which is the 2nd of the triplet.

Then we iterate from the first element of the array to the last element of the array. For each item

1, If the item is smaller than minOne, we assign minOne to item because minOne records the minimal first item of the triplet

2, If the item is larger than minOne, we assign minTwo to Math.min(minTwo, item) because it means that it can be the 2nd item of the triplet and we use Math.min to find the smaller minTwo

3, If the item is larger than minTwo, we can say that we found the triplet and then we can return true to say there exists a triplet.

Until the end, we return false as we cannot find a triplet which increases.

Now it is the code show (in Java)

public boolean increasingTriplet(int[] nums) {

if (nums == null || nums.length < 3) {

return false;

}



int minOne = Integer.MAX_VALUE;

int minTwo = Integer.MAX_VALUE;



for (int num : nums) {

if (num < minOne) {

minOne = num;

}



if (num > minOne) {

minTwo = Math.min(num, minTwo);

}



if (num > minTwo) {

return true;

}

}

return false;

}

The one-way iteration takes O(n) time and we defined extra two variables minOne and minTwo which takes O(1) space.

And this is kind of dynamic programming which basically calculate the current result based on previous calculated result

Hope you enjoy this!
Maps in dart
By: Jay Tillu
Tags: Coding, Mobile App Development, JavaScript, Arrays, Dart

Just like List, Map is also a type of collection. In Maps data is stored in key: value pairs. Keys and values can be of any type.

The map is a growable collection that means it can shrink and grow at runtime.

Map can contain NULL value as well.

There are two ways to declare maps:

Using Map Literal Using Map constructor

Using Map Literal

Just like we declare list using var keyword, we can also use var for declaring Maps.

The main difference between declaration is, for declaring list we use [](square brackets), but to declare maps we have to use {}(curly braces).

for declaring list use [ ]

for declaring map use {}

Syntax for declaring map through variable

Sample code for declaring Map through variable

Sample program to show map in dart.

Syntax for Adding value to Map at Runtime

Sample code for adding value to Map

Sample code to add values in Map at Runtime

Map Constructor

For declaring Map we can also use Map() constructor. It’s just which way you like. There nothing wrong if you declare map using standard method.

Syntax for declaring map through Map constructor

Sample Code for declaring map through Map constructor

Sample Code for declaring map through Map constructor

So, guys, That’s it for maps. Feel free to let me know if I miss something. Till then Keep Loving, Keep Coding. And Just like always I’ll catch you up in the next article. 😊

Remember no teacher, no book, no video tutorial, or no blog can teach you everything. As one said Learning is Journey and Journey never ends. Just collect some data from here and there, read it, learn it, practice it, and try to apply it. Don’t feel hesitate that you can’t do that or you don’t know this concept or that concept. Remember every programmer was passed from the path on which you are walking right now. Remember Every Master was Once a Beginner. Work hard and Give your best.

For More Information Check Out Below Links
Find the Most Frequently Occurring Element in an Array With Ruby
By: Dallas Bille
Tags: Ruby, Programming, Methods, Arrays, Hashes

Method 1.

The first method I’ll use converts the array into a hash with values. We assume you understand how to set a hash’s keys and values. What this method does is iterates over the array, sets an element of the array as a key for the hash, and, for each element’s occurrence, increases its value by one. So if it comes across a pet that exists already in the hash, it increases that pet’s value by one, while keeping the key unique.

Here is what the first method looks like:

pet_count = Hash.new(0)

pets.each {|pet| pet_count[pet] += 1}

pet_count.sort_by { |pet,number| number}.last[0]

Let’s break it down a little bit.

pet_count = Hash.new(0)

#creates a new hash, sets its default values to 0. pets.each {|pet| pet_count[pet] += 1}

#iterates each element, sets our empty hashes key to that of a pet. # “+=“ is the operator on the value of a keys occurrence in the hash.

(E.g., the first iteration: pet_count = {“dog” => 1 } . This is the first occurrence of “dog.”)

If our second iteration contains the same element of a key in our hash, then it adds 1 to that key’s value, while keeping the key unique, which is what happens. (E.g. the second iteration: pet_count = {“dog” => 2} . This is the second occurrence of “dog.”)

Our third iteration sets a new key and a new value since the next element in our carols_pets array is new to our hash. Our hash doesn’t contain a key of “cat” so a new key is created and a value automatically set to 1. Now our pet_count = {“dog”=>2, “cat”=> 1} .

To me this is beautiful. It touches on iteration and the structure of hash creation with key- and value-setting in a block. If you are new to operating on arrays and hashes, this is a good method to dissect. It’s also satisfying to view the result. Which is this:

pet_count = {“dog"=>6, "cat"=>3, "bird"=>3, "chinchilla"=>1, "rat"=>2, "hamster"=>2, "snake"=>1, "mouse"=>1, "spider"=>1}

As you can see, our hash is not quite in order.

Now we can operate on this hash to return the most commonly occurring pet, using the method below.

pet_count.sort_by{|pet,number| number}.last[0]

#hash gets sorted by number

Now let's break this down a little bit:

.sort_by is a hash method, and the block is what the hash gets sorted by (number of times a pet occurs).

If we just ran:

pet_count.sort_by {|pet,number| number}

#returns

[["snake", 1], ["spider", 1], ["mouse", 1], ["chinchilla", 1], ["rat", 2], ["hamster", 2], ["bird", 3], ["cat", 3], ["dog", 6]]

The default sorting with this method for integers is low to high so actually the last key-value pair is the most commonly occurring. All you have to do is call the method “last.”

pet_count.sort_by{|pet,number| number}.last

returns [“dog”=> 6]

All you have to do is add on [0], which operates on an array index number.

pet_count.sort_by{|pet,occurrences| occurrences}.last[0]

returns "dog"

There we go. We have our most popular pet. It’s a little lengthy and complicated, though.
Write a Rock Paper Scissors game without if/else in JavaScript
By: Lilian Lin
Tags: Arrays, JavaScript

In my first JavaScript course, the instructor asked us to write a ‘rock paper scissors’ game between users(us) and computer. I believe a lot of JavaScript learners have written their own version of this game before.

This was my previous solution:

/* step1: Use build-in function - prompt() to return user's choice and store it in the variable - userChoice. */ let userChoice = prompt('please choose one from rock, paper or scissors, and type into the box below'); /* step2: in case user's input has different cases, to be more specific, uses .toLowerCase() convert all return values into lower cases. */ userChoice = userChoice.toLowerCase(); /* step3: building an array, declared as choiceStack to let computer choose from */ let choiceStack = ['paper', 'rock', 'scissors']; /* step4: make use of two JS build-in functions - Math.random()(to generate random number between 0-1), multiply it by 3, because we have 3 choices in our choiceStack array; and pass it into Math.floor()(to return the largest integer less than or equal to a given number) */ let randomNum = Math.floor(Math.random() * 3); /* step5: pass the generated number as an index to choiceStack, to get the element in the array and store it in another variable - computerChoice */ let computerChoice = choiceStack[randomNum]; /* step6: log the result on the console */ console.log(`Your choice is ${userChoice}, the computer's choice is ${computerChoice}.`); /* final step: Compare each choice with if/else statement, then print the result on the console */ if (userChoice === computerChoice){

console.log("Tie!"); }else if (userChoice === 'paper' && computerChoice === 'rock'){

console.log("You win!"); }else if (userChoice === 'rock' && computerChoice === 'scissors'){

console.log("You win!"); }else if (userChoice === 'scissors' && computerChoice === 'rock'){

console.log("You lose!"); }else if (userChoice === 'rock' && computerChoice === 'paper'){

console.log("You lose!"); }else if (userChoice === 'paper' && computerChoice === 'scissors'){

console.log("You lose!"); }else if (userChoice === 'scissors' || computerChoice === 'paper'){

console.log("You win!"); }else{

console.log("Invalid input, please try again");

}

Wow, the code seems a bit long, right? That’s because I have to list all the possible combinations with the if/else statements. The program ended up with tons of ‘if’, ‘else’, ‘userChoice’, ‘computerChoice’,……etc.
Common JavaScript Mistakes — Part 1
By: John Au-Yeung
Tags: Generator, Programming, JavaScript, Arrays, Object Oriented

Mismatching Quotes and Parentheses

JavaScript lets us use single quotes, double quotes, and backticks for strings. They are equivalent. However, we should open and close with the same character. So if we open a string with a single quote, then use a single quote to close a string. If we start with double quotes or backticks, then use those respectively to close the string. Also, special characters like quotation marks have to escape to be included in a string in some cases. If you open a string with single quotes and you also use single quotes in a string, then you have to escape that to include them in the string. This also applies to double quotes and backticks. If you use double quotes in a double-quoted string, then you have to escape it. And if you use a backtick in a template string, then you have to escape the backtick character.

In if statements, parentheses always have to wrap around the whole condition. For example, something like

if (x > y) && (y < 10) {...}

won’t work. The correct way to write that statement is to write is

if ((x > y) && (y < 10)) {...}

if we want to check that both conditions are true.

We can easily avoid this by using a JavaScript code-aware text editor, like Visual Studio code, which will highlight these syntax errors for us so that we can fix these mistakes and make the code run.
【JavaScript】【Leetcode】Shuffle the Array
By: Samuel Chin
Tags: Leetcode, Leetcode Easy, Arrays, JavaScript

題目連結

https://leetcode.com/problems/shuffle-the-array/

題目難度

Easy

題目說明

Given the array nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn].

Return the array in the form [x1,y1,x2,y2,…,xn,yn].

給一個數量為2n的陣列如下：

[x1,x2,…,xn,y1,y2,…,yn]

將其轉換為[x1,y1,x2,y2,…,xn,yn]後return

題目範例

Input: nums = [2,5,1,3,4,7], n = 3

Output: [2,3,5,4,1,7]

Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].

解題思路

第一種：

假設nums = [0,1,2,3,4,5], n=3，那原本陣列與排序過的陣列比較如下：

原陣列：[0, 1, 2, 3, 4, 5]

新陣列：[0, 3, 1, 4, 2, 5]

index值變化：

0：0→0

1：1→2

2：2→4

3：3→1

4：4→3

5：5→5

當index<n時：

new index = index*2

而當index≥n時：

new index = (index-n)*2+1

因此，可得出解答如下：

var shuffle = function(nums, n) {

let newArray=[]; //宣告新陣列，存放new array

for(i=0;i<nums.length;i++){

if(i<n){

newArray[i*2] = nums[i]; //當index<n

}else{

newArray[(i-n)*2+1] = nums[i]; //當index≥n，

}

}

return newArray; //回傳結果

};

第二種：

一樣假設nums = [0,1,2,3,4,5], n=3。首先，我們先來模擬程式一步一步執行找出規則：

第一步：[0]->original index=0

第二步：[0,3]->original index=3=0+3

第三步：[0,3,1]->original index=1

第四步：[0,3,1,4]->original index=4=1+3

第五步：[0,3,1,4,2]->original index=1

第六步：[0,3,1,4,2,5]->original index=5=2+3

於是，我們可以用push()的方式，在push第一個數字完之後，對第一個數字的index值+3後再push一次，得出解法如下：
Merging Arrays [problem][solver]
Tags: Algorithms, JavaScript, Arrays, Median, Merge Sort

The ability to merge two arrays together can prove quite handy. They can help us solve algorithmic problems such as tackling the merge sort or they can provide assistance with a slightly more complicated problem, such as, finding the median of two sorted arrays. Let’s discuss what each problem is trying to accomplish.

The Merge Sort in our case is accomplished by breaking up our arrays into individual element arrays. No matter what number you have in this array, it is always sorted. Once this structure is in place we need to merge them back in order, so we can obtain a sorted array. Think of it like subway cars being decoupled into its individual train car and then linked back up again.

The way in which the arrays are ‘decoupled’ are by successively dividing each array in half until you only have either one or zero elements left. The description above should hint towards recursion in our implementation.

Let’s look at a simplified example of the merge sort. If we start with one unsorted array, at the end, we should end up with a sorted array:

arr = [1,5,7,2,4,6] => left = [1,5,7]

right = [2,4,6]

=> sortedArr = [1,2,4,5,6,7]

Our unsorted array will not stop at the first left and right displayed above, rather it will keep dividing the arrays in half, and comparing each left item to its corresponding right item based on values(left[i] compared to right[j], i and j representing the indices of the values they contain), until they reach a zero or one item array, by that time we will have a newly sorted array because we will be pushing those compared values into a new array. This will make much more sense when we display the code below.

The merge portion of the code will look for the following scenarios present in the arrays:

when left item is smaller than right item when right item is smaller than left item when the values of both left and right are equal when left and right array sizes are not the same if one of the arrays are empty

Here is the mergeSort code for you to try in your favorite editor:

The second problem shows how to take advantage of the same merge code to apply in finding the median value of two sorted arrays.

The first step is recognizing that you cannot calculate the median value of two arrays, it has to be one sorted array.

The second is understanding that median values are different based on the length of the array being either even or odd. If the array length is odd, the median will correspond to the middle value. If it’s even the median will be an average of the sum of the two middle numbers.

Understanding this makes a very difficult problem very easy to tackle. Try the below code in your favorite editor.
Rotate Image
By: Chenyun Zhang
Tags: Leetcode, Leetcode Medium, Arrays

leetcode 48

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

To solve the question we can first reverse the matrix, which will give us the following:

matrix.reverse()

After we reverse the matrix, we can see that we still need to exchange 4 with 8, 9 with 1, 6 with 2. We can do that by looping through the matrix to exchange the element:

for(let i=0;i<matrix.length;i++){

for(let j=i;j<matrix[i].length;j++){

let temp = matrix[i][j]

matrix[i][j] = matrix[j][i]

matrix[j][i] = temp

}

}

This will get us:

And, that’s it!

The final result:

var rotate = function(matrix) {

matrix.reverse()

for(let i=0;i<matrix.length;i++){

for(let j=i;j<matrix[i].length;j++){

let temp = matrix[i][j]

matrix[i][j] = matrix[j][i]

matrix[j][i] = temp

}

}

};

Give me some likes if you like the solution, let me know how you think.
How to Insert and Delete Array Elements in JavaScript
By: Mohammad Anisul Islam
Tags: Javascript Tips, JavaScript, Array

Insertion and deletion are some of the most important operations in JavaScript array. We can achieve this by using different string methods.

Now we will see some such JavaScript methods.

Insert at the beginning

To add an element o the beginning of an array we will use unshift() method.

let anArray = [1, 5, 8];

anArray.unshift(30);

console.log(anArray);

//Output:[ 30, 1, 5, 8 ]

Delete from the beginning

To delete an element from the end of an array we can use shift() method.

let anArray= [1, 5, 8];

anArray.shift();

console.log(anArray);

//output:[ 5, 8 ]

Inserting at the end

By using push() method we can add an element to array at the end.

let anArray= [1, 5, 8];

anArray.push(10);

console.log(anArray);

//Output: [1, 5, 8, 10]

Deleting from the end

By using the pop() method we can delete an element from the end of an array.

let anArray= [1, 5, 8, 10];

const popped = anArray.pop();

console.log(anArray)

//Output: [1, 5, 8]

Deleting by delete keyword

There is a special keyword called delete. Using this operator we can delete an element but space will not be removed.

let anArray= [1, 5, 8];

delete anArray[2];

console.log(“After deletion:”, anArray);

//Output: After deletion: [ 1, 5, <1 empty item> ]