fabiochiu/medium-articles huggingface dataset:
Understanding Splice: Javascript Arrays
By: Christopher Clemmons
Tags: Web Development, JavaScript, Arrays, Computer S, Software Engineering

Photo by Markus Spiske on Unsplash

The splice() method allows you to make changes to the contents of an array by removing or replacing existing elements and/or adding new elements in place. If you’re building out a website or application that allows users to type and search for things, assist them in finding products based on their needs and wants and many other things. Arrays can be used for many other things rather than filters. Arrays have their place in a lot of server-side programming as well.

Splice accepts three parameters, which are the arguments that this method will take to complete your requested task(s).

Start — optional

“Start” is the first parament that splice will accept. This is the number of the index you choose to start from. All this is doing is going to index 1, placing “newPerson2” in that index and not removing any of the elements but instead it’s moving it over basically.

Delete Count — optional

This is the second parameter that accepts a number and it represents the number of elements you are planning on replacing starting from the index you have chosen. If you select a number that is larger than the number of elements that currently exist, all those elements will be removed and replaced with the element you’re inserting.

Item

This is the actual element that you will place into your array. This is necessary for adding new elements into your array. If you choose not to add this parameter, the splice method will only remove items from your array. Using splice with a number only as the main parameter will select the element’s position in the array but not the index. For example, array.splice(1), will return the first item of your array. Array.splice(2), will return the first two elements in your array. Since you’re not inserting any new variables by doing this, you won’t have to specify the index of where that element is located.

let array = ['person1', 'person2', 'person3']; array.splice(1, 0, 'newPerson2'); //Expected output ---> "person1, newPerson2, person2, person3

Conclusion

For more of my blogs and tutorials, follow me on here!
Await Array.Prototype.Map with ES6
By: Rémy Villulles
Tags: Promises, Asynchronous, JavaScript, ES6, Arrays

Photo by Paras Katwal from Pexels

Promises can be really tricky to understand in Javascript. Should we use Promises or the combo async/await? It can be a tough choice.

But when it gets to doing functional programming, it can start to be confusing. What if your callback is dealing with asynchronous functions and you’d like to await them? How can you then deal with the return value of your Map callback? (Which will be a Promise as the callback is async)

Unfortunately, even if it’d make sense, the usage of await directly on the Map is not possible. Let’s get the following scenario:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; async function test() {

const results = await array.map(async(item) => { // The setTimeout with await simulate a "heavy async function"

await setTimeout(() => {}, 1000);

return item;

})



console.log(results);

} test()

The console.log will print an array of promises which still need to be resolved. It’s because Map is not able by itself to resolve the promises, so it’ll just return them and expect the developers to handle them manually.

Now, if we want to wait for all of them to resolve and print them as a result, we can use this very useful function from the Global Object Promise: Promise.all and adding the keyword await behind to wait for all those promises to be resolved.

Now let’s edit our code:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; async function test() {

// No more await here

const promises = array.map(async(item) => {

await setTimeout(() => {}, 1000);

return item;

})



// Await + Promise.all to wait for all promises to resolve

const results = await Promise.all(promises)



console.log(results);

} test()

With this new version of the code, we are waiting for all promises to resolve and then we can print their result correctly!
Remove duplicate objects from an Array of Objects(Javascript-ES6)
By: Jithin Sebastian
Tags: JavaScript, ES6, Arrays, Objects, Iteration

Duplication array --> Unique array

Let’s assume we have an array of objects in the following format.

let employInfo = [ { id: 1, name: 'Sam', email: 'sam@test.com', designation: 'Manager' }, { id: 2, name: 'Ram', email: 'ram@test.com', designation: 'Developer' }, { id: 3, name: 'Jacob', email: 'jacob@test.com', designation: 'EM' }, { id: 2, name: 'Ram', email: 'ram@test.com', designation: 'Developer' }, { id: 3, name: 'Jacob', email: 'jacob@test.com', designation: 'EM' }, { id: 4, name: 'John', email: 'john@test.com', designation: 'Admin' }, { id: 3, name: 'Jacob', email: 'jacob@test.com', designation: 'EM' } ];

The array which we have contains some repeated objects. So we can consider and remove the repetition in two ways.

Repetition in the case of all the properties(keys) in the repeated objects. Repetition based on some of the selected properties.

So both these above cases we need to handle in two different ways.

Solution:

function getUniqueArray(arr=[], compareProps=[]) {

let modifiedArray= [];

if(compareProps.length === 0 && arr.length > 0)

compareProps.push(...Object.keys(arr[0]));

arr.map(item=> {

if(modifiedArray.length === 0){

modifiedArray.push(item);

}else {

if(!modifiedArray.some(item2=>

compareProps.every(eachProps=> item2[eachProps] === item[eachProps])

)){modifiedArray.push(item);}

}

}); return modifiedArray;

}

Cases:

Remove the duplication based on all the properties(keys) in the repeated objects

In this case, we should execute the “getUniqueArray” function with our duplicated array of objects only as a function parameter. Which will be like the below format.

getUniqueArray(employInfo);

OutPut:

Remove duplication based on some of the selected properties(keys) in the repeated objects

In this case, we should execute the “getUniqueArray” function with our duplicated array of objects and the required compare properties(keys) in an array format as function parameters. Which will be in the following format.

let compareProps = ['id', 'name', 'email']; // 'designation' property is not using for remove duplication.

So here we are going to remove the repeated objects based on the above compareProps(keys) only. Which means we are not checking all the properties in each object.

Sample input Array : var employInfo = [ { id: 1, name: 'Sam', email: 'sam@test.com', designation: 'Manager' }, { id: 2, name: 'Ram', email: 'ram@test.com', designation: 'Developer' }, { id: 3, name: 'Jacob', email: 'jacob@test.com', designation: 'EM' }, { id: 2, name: 'Ram', email: 'ram@test.com', designation: 'Sofware Engineer' } ]; getUniqueArray(employInfo, compareProps);

OutPut:

That’s it, Pretty cool. Right?

If you found this article is interesting and helpful to you, then please support and follow me on LinkedIn.
6 different ways to loop through an array in JavaScript (with examples)
By: Jack Tiong
Tags: Js, Arrays, JavaScript, Loop

3. forEach()

The forEach() is an array’s method that uses a callback function to include any custom logic to the iteration. In other words, forEach() will execute the provided callback function once for each array element.

The forEach() method has the following syntax:

array.forEach(callback(currentValue [, index [, array]])[, thisArg]);

callback — refers to the callback function that takes up 3 arguments:

1. currentValue — the data/value of the current element

2. index (optional) —the array index of the current element

3. array (optional) —the entire array object

— refers to the callback function that takes up 3 arguments: 1. — the data/value of the current element 2. —the array index of the current element 3. —the entire array object thisArg (optional) — Value to be passed to the callback function which will be used as its this value.

Value to be passed to the callback function which will be used as its value. Return — undefined

Note: There’s no way we can break a forEach() loop.
5 must-know array methods in React
By: Raymond Akalonu
Tags: Array Methods, React, JavaScript, Arrays, Reactjs

Improve your skills as a react developer

React is the most popular front-end library at the moment. This makes it very important to understand some core concepts that will help you improve your development process. In this blog post, I’ve compiled some very popular array methods that are frequently used in react project. I trust you'll find this very helpful.

First off, let’s consider what is an array method. Simply put, an array method is a method that can be called on an array to perform an action on or with that array. Here are a few javascript array methods used in react.

.map()

This array method takes in a function that will be called on each element in a given array and it returns a new set of an array without modifying the original array. Simply put, it helps us create a new set of array based on an existing one.

Quick Example

The code snippet below shows a new set of an array after using the map method to add 3 to each element in the numbers array.

const numbers = [1, 3, 5, 7];

const newNumbers = numbers.map( number => number + 3);

// newNumbers will be equal to ['4', '6', '8', '10']

.reduce()

This is a great array method that uses an accumulator to reduce all elements in an array to a single value. It basically takes in two augments, a callback function and an initial value, performs an action, and returns a single value, the value being any type i.e. object, array, string, integer. The call back function takes in two parameters namely: accumulator and current value.

Quick Example

The code snippet below shows a single or the cumulated value being returned, after using the reduce method to add the accumulated value with the current value, the function is iterating over.

const numbers = [1, 2, 3, 4, 5]; const newValue = numbers.reduce( (accumulator, currentValue)=> accumulator + currentValue); console.log(newValue); // newValue will return 15

It is also worthy of mentioning that there are other cool features you can use the array method to do. For more on that, check the MDN docs for example of that. Be sure to thank me later😁

.filter()

Just as it sounds, it works similar to the way the .map() method works. It filters an array based on if an element in the array, meets the condition passed in the function and then, it returns an array.

Quick Example

const numbers = [1, 2, 3, 4, 5, 6, 7]; const newValue = numbers.filter( (number)=> number >= 3); console.log(newValue); // newValue will return [3, 4, 5, 6, 7]

.includes()

This method simply checks if an element exists in a given array and returns a boolean(true or false). Do note that there are some constraints with regards to the data types that the include method can check for. This is because of the way Javascript treats objects and primitive types.

Quick Example

const numbers = [1, 2, 3, 4, 5]; const newValue = numbers.includes(3); console.log(newValue); // newValue will return true

.find()

This method takes in a function that checks for a specific element in an array and returns the very first occurrence of the condition.

Quick Example
Be careful: Doctrine Collection is not a native array
By: Pedro Carlos Abreu Jiménez
Tags: Arrays, Doctrine, Symfony, PHP

PHP define array as “an ordered map. A map is a type that associates values to keys”. It is one of the key point of php language. But work with array through all the array functions could be a little hard when we are dealing with objects.

To solve some of those problem Doctrine Project created Collection to work with its entities. Collections are a good OOP implementation of list of objects and have many features included. This interface is implemented on Doctrine\Common\Collections\ArrayCollection and you could use it in your project as much as you want to work with list.

$users = new ArrayCollection([$user1, $user2]);

But careful, you have to keep in mind that ArrayCollection is not an native array. Some function like in_array do not accept ArrayCollection. This is easy to solve by calling toArray() method.

$users = $users->toArray();

But the main problem is when you pass the collection as parameter.

function setUsers(Collection $users); //vs function setUsers(array $users);

Working on a project for https://www.tourknife.com/ with had a problem of duplication of intances when we change from using array to ArrayCollection for simplicity. The problem is that we added a list of object to diferent processor to do its work and we end up with more intances that we passed originally. To avoid this problem with have to or even clone the array on every method or just pass the native array.

This happen because when you pass a native array you are passing a copy of the array, when you pass an ArrayCollection you are passing a reference to that object and any change you do over this array will offect reference.

So ArrayCollection is not an array it’s an object.
Vuejs object updating inside Vuex array: CRUD
By: Fthi Arefayne
Tags: Vuejs, Vue, Arrays, Objects, Vuex

Vuex state management and interactions

Vuex is a state management library for Vuejs applications by providing a central data store with consistent ways of updating an object of an array inside the state of the Vuex store.

Components of a Vuejs application may call and use the defined actions to trigger or dispatch mutations that actually poses a first-hand access to the state of the Vuex store. Upon changes to the state of the store components can fetch the updated state for view.

The goal of this article is to discuss the proper update of an object inside the array using mutations and actions. Setting up a project with Vuex and Vue will give us a project structure that looks as like this.

Project folder structure

Here is a snippet of the App.vue component where we fetch and display the array of items from our store. Each item is described as an object with a text attribute. For instance: text: “vuex wins”. The array holds all the item objects wherein each object has a text attribute. The challenge we have picked up today is updating the text of a specific object in the middle of the array.

/!-- App.vue -->

<template>

<ul>

<li v-for="(item, index) in loadItems" :key="index" >

<span @dblclick="enterEditing(index)">{{item.text}}</span>

<input v-show="edit" :value="item.text" @keyup.enter="updateItem">

</li>

</ul>

</template>

<script>

export default {

data() {

return {

edit: false

}

},

methods: {

updateItem(e) {

const newValue = e.target.value.trim()

this.$store.dispatch('updateItem', {

index: this.newIndex,

text: newValue})

.then(() => {

this.edit = false

})

}

},

}

</script>

The actions and mutations of the Vuex implementation understand each other using mutation types definition. Here we will focus on the update aspect of the CRUD operations. The rest of the CRUD is available in the full implementation available on Github. Most of this is inspired from a Stack overflow post and the official Vuex todos application.

<!-- store/mutation-types.js -->

export const UPDATE_ITEM = 'UPDATE_ITEM'

<!-- store/actions.js -->

export const updateItem = ({commit}, newUpdate) => {

commit(types.UPDATE_ITEM, newUpdate)

}

<!-- store/mutations.js -->

[types.UPDATE_ITEM] (state, payload) {

Object.assign(state.Items[payload.index], { text: payload.text });

// Other ways to update

// this.Items[payload.index].text = "CHANGED";

// Vue.set(this.Items, payload.index, { text: "CHANGED" });

}

I hope this helps fellow developers in their projects. Here is the source code links.
[JS] 陣列筆記
By: Greta Ma
Tags: JavaScript, Arrays, 陣列, Js, 前端

陣列的寫法

如何建立陣列

建立陣列的方法就跟宣告變數一樣，也會賦予它一個名字，使用 var 關鍵字，後面接上陣列名稱。指定給陣列的值會放在方括號中，每一個值中間用逗點隔開。

範例如下：

有三個玉米田，分別種出 8 個、5 個、6 個玉米

var cornField = [8,5,6];

有兩隻狗，分別叫做 John 跟 Bob

var dogs = ['John' , 'Bob'];

如何讀取陣列的值

陣列中每一個資料項目都會被自動給予一個編號，這個編號稱為索引（index），第一個值編號為 0，第二個值編號為 1，以此類推。索引可用來存取陣列中的指定項目。

var cornField = [8,5,6];

console.log(cornField[0]);

// 得出的值就會是 8

如果在選取陣列時，沒有寫到索引值的話，讀出來的結果就不會是值，而是整個陣列的內容。

console.log(cornField);

// 讀取結果：[8,5,6]

當然，也可以用變數儲存陣列中指定項目的值，並呼叫出來。

var cornField = [8,5,6];

var cornField2 = cornField[1];

console.log(cornField2);

// 得出的值就會是 5

如何在空陣列新增值

先宣告一個空陣列

var cornField = []; 使用 push 方法依序新增值進去

push 也可以新增字串、函式、物件進去陣列裡喔。

cornField.push(5);

cornField.push(8);

cornField.push(6);

console.log(cornField);

// 得到的結果就會是 [5,8,6]

3. 或是直接指定新的值

cornField[3] = 100;

// 直接新增第四個值為 100

如何修改陣列中的值

跟操作變數一樣，將新的值指定給該資料項目。

以修改陣列第一個值為例：

cornField[0] = 10;

// 把第一個值由 5 改成 10

查詢陣列中有幾個值：length

在陣列後面使用 length 特性可以得知該陣列的長度，亦即該陣列中共有幾個值。後面學到 for 迴圈時會很常用到。

console.log(cornField.length);

從陣列中過濾資料：filter()

filter 方法可以從 A 陣列中過濾出符合條件的資料，並成立新的 B 陣列來放置過濾出的資料。此方法會帶出一個匿名函式，過濾資料的條件會寫在函式的裡面，前面加一個 return，表示此函式將會回傳條件為 true 的資料。

以下範例引用自王志誠老師 a.k.a 卡斯伯的文章：JavaScript 陣列處理方法 [filter(), find(), forEach(), map(), every(), some(), reduce()]。

原始陣列資料：

var people = [

{

name: 'Casper',

like: '鍋燒意麵',

age: 18

},

{

name: 'Wang',

like: '炒麵',

age: 24

},

{

name: 'Bobo',

like: '蘿蔔泥',

age: 1

},

{

name: '滷蛋',

like: '蘿蔔泥',

age: 3

}

];

使用 filter() 過濾資料：

var filterEmpty = people.filter(function(item, index, array){

});

console.log(filterEmpty); // 沒有條件，會是一個空陣列

var filterAgeThan5 = people.filter(function(item, index, array){

return item.age > 5; // 取得大於五歲的

});

console.log(filterAgeThan5); // Casper, Wang 這兩個物件

var filterDouble = people.filter(function(item, index, array){

return index % 2 === 1; // 取得陣列中雙數的物件

});

console.log(filterDouble); // Wang, 滷蛋 這兩個物件

函式中的參數 item、index、array 分別代表「原始陣列的值」、「原始陣列值的索引」、「原始陣列的名稱」，後兩者為選擇性的，可不帶入。（參考資料：Array.prototype.filter() — MDN）
4 Best Methods to Search Data in Your JavaScript Arrays
By: Piero Borrelli
Tags: Technology, Web Development, Programming, JavaScript, Arrays

4 Best Methods to Search Data in Your JavaScript Arrays

Photo by Amit Lahav on Unsplash

“What’s the best way to do this?”

This is a question I’m sure you have asked yourself a hundred times using JavaScript. And that’s because this language has so many different ways of doing anything.

If you’re working with arrays, you will often have to search through them. But what’s the best way to do that?

What if you need to know if a value is present in an array? What if you want to filter something out of your collections?

Turns out that in this sea of information, JavaScript has 4 amazing methods to do anything you may need when searching through your arrays.

Let’s start.

Use includes()

The includes() method returns a boolean telling you if the passed-in parameter exists or not in an array.

In my example, I’ve used this method to ask the question: “Hey array, do you contain this value, yes or no?”

An extra important thing to note about this method is that it doesn’t implicitly perform type coercion on the value you pass in. So basically, it won’t modify the type of parameter you pass in to confront values.

As you can see, a strict comparison is performed here, so the number 4 won’t be converted to the string '4' to test the condition.
How to use arrays and loops in JavaScript
By: Sylvia Antons
Tags: Arrays, JavaScript, Loops In Javascript

Arrays and loops is a new data structure that is used all the time within developers, they allow us to create collections of data in a much easier way than creating different variables.

For example, these are strings: 👇🏼

let name = “Sylvia”; let year= “2021”;

But the problem is that what if we need to have multiple names or multiple years or temperatures, what if we want an easy collection of data. That is why we use array []. The rule of using array[] 👇🏼

let countries = [“Germany”, “Iceland”, “Spain”];

How to read an specific item of an array, you will have to use a [], but see which is the first item, an array index always starts from 0. So if you want to access to “Iceland” than you write:

countries[1];

To know the length from your code you use the word .length

countries.length

if we want to replace an item inside an array,

cities[2] = “USA”;

so Spain becomes USA

Looping thru each country in the array, we need to use a new function forEach 👇🏼

cities.forEach(showCountry);

How to create an array with the all the days of the week and console log it:

now log Monday and Sunday:

Logging every day of the week in a sentence:

👇🏼
Simple Data Structure
By: Yatin Mishra
Tags: Java, Arrays, Placement, Linked Lists, Data Structures

The term Data Structure means data collection with well defined operations and behavior or properties.

The term Linked list refers to a linear data structures with non contiguous memory.

Or

The linked list is a collection of linear data elements called node stored in a non contiguous memory(Stored randomly anywhere in the memory).

Note: If the data is stored randomly anywhere in the memory how to access it, we have Linked List to overcome this problem, it is linked with the help of address where each block carries address of successive block or previous block or node.

A node contains two parts :

i: data

ii: address

Advantage over arrays:

i : Arrays does not have dynamic memory

ii : Easily insertion/Deletion

Linked List

There are four basic Linked list

SLL(Singly Linked List) CLL(Circular Linked List) DLL(Doubly Linked List) CDLL(Circular Doubly Linked List)

Linked List Image (Source : AlphaCodingSkills)

1.Singly Linked List

In Singly Linked List the very first node is called or pointed as Head and if you want to know the last node it points to null.

Note : The node part contains the address of the successor node so we can not traverse in reverse direction to overcome this problem we have Doubly Linked List lets see how.

class LinkedList

{

Node head;

class Node

{

int data;

Node next;

Node(int d)

{

data = d; next = null;

}

}

}

2.Doubly Linked List

It also contains nodes. There is one data and two address pointers in a single node in which one address which points to its previous node, and one points to the next node.

Doubly Linked List

You can see in the picture that each node contains one data and two address one points to the address of next node and one points to the address of previous node. The first and last node points to the null. In the very first node the prev address shows null as it does not have any previous value and in the very last node the next pointer shows null value.
Minimum Waiting Time with Time and Space Complexity — Competitive Programming
By: Code Wrestling
Tags: Sorting, Time And Space Complexity, Interview Preparation, Competitive Programming, Array

You’re given a non-empty array of positive integers representing the amount of time that specific queries take to execute. Only one query can be executed at a time, but the queries can be executed in any order.

A query’s waiting time is defined as the amount of time that it must wait before its execution starts. In other words, if a query is executed second, then its waiting time is the duration of the first query; if a query is executed third, then its waiting time is the sum of the duration of the first two queries.

Write a function that returns the minimum amount of total waiting time for all of the queries. For example, if you’re given the queries of durations [1, 4, 5], then the total waiting time if the queries were executed in the order of [5, 1, 4] would be (0) +(5) + (5 + 1) = 11. The first query of duration 5 would be executed immediately, so its waiting time would be 0, the second query of duration 1 would have to wait 5 seconds (the duration of the first query) to be executed, and the last query would have to wait for the duration of the first two queries before being executed.

Note: you’re allowed to mutate the input array.
What is an Array in Java ?
By: Jin Hyuk Park
Tags: Java, Programming, Arrays, Data Structure Algorithm

What is an Array ?

- Arrays are mostly used to store multiple items in a single variable.

- Arrays are useful when grouping multiple items for easier access.

!!!NOTE: Array in Java != Array in JavaScript

How to Create an Array:

First of all, all items inside of an array have to have same data type.

EX) String, Integer, Boolean etc…

When creating an array, the data type has to be specified.

EX) String rides[] = {“car”, “bicycle”, “skateboard”};

EX) int grades[] = {86, 72, 99, 100, 84, 92};

How to Access Elements:

When accessing elements of an array, we can simply use [index].

!!!NOTE: First element of an array has an index of 0 NOT 1.

First element has an index of 0 so we can use index of 0 to get the first element of an array.

EX) rides[0]; // returns car;

EX) grades[2]; // returns 99;

We can also use for-loop to iterate through an array.

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

System.out.println(i);

}

// the above for-loop will print out every element of a rides array.

It is also possible to make Multi-Dimentional array.

EX) int height [] = {{1,2,3,4,5}, {11,22,33,44,55}};

To access the elements of Multi-Dimentional array, we can use [] again.

EX) height[0][0] // returns 1. first [0] is the first array in height array which is {1,2,3,4,5} and the next [0] is the first element of {1,2,3,4,5} which is 1.
Leetcode 33. Search in Rotated Sorted Array
By: Bhanuprakash Devapatla
Tags: Coding, Tech Interview, Algorithms, Binary Search, Arrays

The ask is to solve the problem in log(n) time. Let’s see how it can be done.

Essentially we have to find an element, let's call it pivot, in the ascending sorted and rotated array such that it satisfies following invariance:

Invariance

nums[i] > nums[pivot] < nums[j] where pivot = i+1 and j = pivot+1 (imagine [3,4,5,1,2] or [5,1,2,3,4])

Once we find the pivot — it divides the array into 2 sorted parts First part: [0,pivot) and second part: [pivot,n) where n is the length of array.

Searching for target in each of these 2 sorted parts takes log(n) time because we can use binary search.

So if we can solve the finding pivot problem in log(n) time then the total run time of complete algorithm is going to be 3log(n). This is as follows:

log(n) to find pivot + log(n) to search for target in first sorted part + log(n) to search for target in the second target part = 3log(n)

How do we find pivot in log(n) time?

Yes, we have to split for array into two at each iteration and find the element that satisfies the aforementioned invariance.

While searching for pivot we have to take care of conditions when the size of subarray that we are searching is less than 3 Think: The invariance needs 3 elements, what if we don’t have 3+ elements in our array

Here is one possible algorithm to find pivot:

Here is another thing to consider.

What if the input array is not pivoted or pivoted by 0 elements?

Actually it’s no problem at all (does this remind you of Prof Sedgewick?) since the special 1 element case and 2 elements case are going to take of non-pivoted arrays neatly.

Complete implementation of LC 33

Suggestions and comments are welcome!!
Maximize Sum Of Array After K Negations
Tags: Arrays, Coding Problems, Interview, Leetcode Easy

Given an integer array nums and an integer k , modify the array in the following way:

choose an index i and replace nums[i] with -nums[i] .

You should apply this process exactly k times. You may choose the same index i multiple times.

Return the largest possible sum of the array after modifying it in this way.

Example 1:

Input: nums = [4,2,3], k = 1

Output: 5

Explanation: Choose index 1 and nums becomes [4,-2,3].

Example 2:

Input: nums = [3,-1,0,2], k = 3

Output: 6

Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].

Example 3:

Input: nums = [2,-3,-1,5,-4], k = 2

Output: 13

Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4]

Approach 1

Sort the array, then negate all k possible negative number .After negating the negative number, either k numbers are finished negating, in that case return the current sum of the array , or if still some more times of negation still remain, then sort the array again(this is because if a negative number has greater magnitude than other positive numbers in the array , then this could alter the order of sorted array ). Now the least element which is at the first index is negated multiple times , such that k negation are finished , for this mod%2 operation can be used since the cycle repeat for even number of times .

The solution is given below:

def largestSumAfterKNegations(nums,k):

nums.sort()

i=0

while(True):

if(i>=len(nums) or nums[i]>0 or k<=0):

break

if(nums[i]<0 and k>0):

nums[i]=-1*nums[i]

k-=1

i+=1

nums.sort()

if(k==0):

return sum(nums)

else: if(0 in nums):

return sum(nums)

else:

if(k%2!=0):

nums[0]=nums[0]*-1

return sum(nums)

Time complexity: 0(nlgln)

Space :0(1)

Approach 2:

At anytime we would mean to negate the least number currently in the list so that that maximizes the sum.

Take an example

say, nums = [2,-3,-1,5,-4], k = 2 ater step 1 negation



nums=[2,3,-1,5,-4]

after second negation

nums=[2,3,-1,5,4]



sum is 2+3-1+5+4 =13

This idea essentially suggest the usage of min heap or priority queue .

Time complexity: 0(nlgln)

Space :0(1)
Javascript Data Structures pt. 1: Arrays
By: Edwin Ramos
Tags: Programming, Arrays, JavaScript, Data Structures

So what exactly are Arrays?

(thanks to Oracle Java tutorials for the picture)

Arrays are a Data Structure that can hold a number of “things” in order. What “things” are in JavaScript is entirely up to you since Javascript doesn’t force strict typing. It could numbers, characters, strings, booleans, or objects. In Order means that the ordering of the things are set, if you place an integer at the 0 index it will always be there until you say other wise.

Just to go over the diagram a bit, an element is a physical “thing” in an array. An Index is a numbered spot in an array, and you refer to all the indexes(numbered spots) in array as indices of an array. Most languages also have 0-indexed arrays, this simply means that every array starts counting at 0. If you had one thing in an array, its spot would be number 0.

Arrays in Javascript are also dynamic by default but in other languages its not the case, you would something like an ArrayList there.

Just keep in mind that in other languages like C++,Java, Python etc. standard arrays are not expandable once you declare them. If you tell an array in Java that it’s going to have 10 spots, it’s going to only have 10 spots in memory for the array and nothing more, trying to place something outside of the 10th spot or read something outside of will throw you an Out of bounds error.

something like this in java would throw you an error like below, there was only one space in this array.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

at Main.main(Main.java:9)

When dealing with arrays in Javascript we will still come across out of bounds errors, but not when putting something into an array. Only when trying to access something that isn’t there yet. If you have 3 items in an array and ask Javascript for the 4th one it will yell at you like Java did over there.

PLEASE NOTE: It’s uncommon and unnecessary to declare the indices of an array in Javascript like in line 1.

3

true

please don't error out

Should you run the snippet the above is what you’d see in your console.

It seems like an Array in Javascript has some kind of super power over other basic arrays in other languages. This is because actually, all basic arrays in Javascript are Array Objects. It would be unfair to compare an array in JS to an array in Java because they’re two entirely different things. An Array in Java is a primitive type with very basic functionality while an Array in JS is its own entity with seeming very complicated additional properties and methods like the .push and .forEach I use above.

What Javascript does to your basic array declaration

To simply put it, the Array in Javascript is an upgraded version of a basic array that Javascript hands to you out of the box. It is a much fairer comparison to use a Java/Python ArrayList against a Javascript Array.
Spiral Matrix — Day 26(Python). Today, we will be looking into one of…
By: Annamariya Tharayil
Tags: Coding, 365dayschallenge, Arrays, Python, Leetcode Medium

When we think of an array, we should imagine a data structure with contiguous memory allocation. When it comes to a 2D array, each cell is identified using row and column numbers.

To solve the given problem, we just need to learn how we can trace the path in our matrix. I have shown below, how we need to trace path, if we are given a 3x3 matrix.

Tracing the path in 2D matrix

A point to notice, once we traverse through a row or a column, we would never visit that row/column again. We need to keep track of rows/columns that we have already traversed. We can hold 4 variables that we keep track of traversed rows/columns. We need to start traversing the array from left to right, then top to bottom, later right to left and finally bottom to top.

The code will look like below.

class SpiralOrderCreater:

def spiralOrder(self, matrix):

nums = []

if(len(matrix) == 0):

return nums

else:

top = 0

bottom = len(matrix) - 1

left = 0

right = len(matrix[0]) - 1

total_nums = len(matrix) * len(matrix[0])

while(len(nums) < total_nums):

for i in range(left,right+1):

if(len(nums) < total_nums):

nums.append(matrix[top][i])

top += 1

for i in range(top, bottom+1):

if(len(nums) < total_nums):

nums.append(matrix[i][right])

right -= 1

for i in range(right, left-1, -1):

if(len(nums) < total_nums):

nums.append(matrix[bottom][i])

bottom -= 1

for i in range(bottom, top-1, -1):

if(len(nums) < total_nums):

nums.append(matrix[i][left])

left += 1



return(nums)

Complexity analysis

Time Complexity

We are looking at each element in our array once, and hence the time complexity is O(m*n).

Space Complexity

We are not using any extra space while finding the solution, except for the output array. We do not consider space used for output array, and hence space complexity is O(1).
Data Structure 101
Tags: Coding Interviews, Algorithms, Programming, Arrays, Data Structures

— — — — — — — — — — — — — — — -

This is a one-stop shop article for all beginners who wish to commence their software engineering journey.

As the name says, ‘Data structure’ is nothing but a method to ‘structure your data’. The next question is why do we need to structure our data? The answer to this question is related to our day to day life. Each activity we perform in our life, is nothing but communication of information (data). Earlier we used to write all the data on paper and keep it in a file but with the invent and discoveries of great minded people we can now save trees and store huge amount of data using computers. Saving this data requires memory, hardware which our hardware engineers create, but how to store / access / query / use this data is the job of a software engineer. Hence, if you wish to become a kick-ass software engineer spending time and exploring data structure will help you.

Below is the list of the most common data structures -

Array Linked List Stacks Queues HashTable HashSet Trees Graphs Trie

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Let’s start our journey …

Arrays

Arrays is one of the most widely used data structure. It is a linear data structure with contiguous memory allocation.

Now let’s try to properly understand the above sentence.

For starters think of array as a list of elements. Each element is assigned an index. Note that the first index of an array is always 0.

In most programming languages, all elements of the array belong to the same data type. Hence, if you define an array of type ‘int’, all elements will be of data type ‘int’. In memory each element of the array will occupy the type ‘int’ equivalent space.

In most programming languages, each element of an array will be stored at a particular address in the memory. For an array, all elements are stored one after the other in the memory. This is a unique characteristic of an array making it contiguous. Hence, if you know the starting address of the array, you can access the 2nd, 4th .. or any indexed element. When we initialize an array, we store the starting address for the array in a variable. Using indexes, we manipulate the address and therefore access/modify the values stored at each index for the array defined.

Arrays in most programming languages can be of two types : static or dynamic. A static/fixed size array will always have the same size and you cannot try to append any element beyond the initial size defined for the array. For a dynamic sized array, the starting address is stored in the variable when initialized, and new elements can be added to the array depending on the requirement and the memory available. Remember array elements require contiguous memory allocation.

Basics to start with an array :

Sort an array Find maximum / minimum element in an array Binary Search Reverse an array Rotate an array by ’N’ number of times

Frequently asked interview questions :
JACL And OCA Work Together at Annual Leadership Summit
By: Jesse Cheng
Tags: Oca, Asian American, Leadership Summit, Jacl

Pins on a world map Photo by Aksonsat Uanthoeng from Pexels

A recent graduate of the University of California, Irvine, Jesse Cheng is on a mission to advocate for minorities and people of color, with a special focus on minority-owned, small businesses. Currently, Jesse Cheng works at Assura Public Relations in an intern role, where he assists companies owned by people of color, intervening with different departments in the city and county government on their behalf. He also takes the time to be involved with community organizations such as the Japanese American Citizens League (JACL) and the Organization of Chinese Americans (OCA).

Original known as the Organization of Chinese Americans, the OCA/Asian Pacific American Advocates is a non-profit organization based in Washington, D.C. Since its founding in 1973, it has promoted the well-being of Pacific Islanders and Asian Americans. The organization is particularly focused on issues involving immigration, fair treatment, education, and broadband access. Members have the opportunity to apply for scholarships, attend annual conventions, participate in professional development opportunities, and even work with the organization in various internships.

Each year, the OCA partners with the JACL for a leadership summit. A 3-day seminar that focuses on advocacy and civil rights, the JACL/OCA Leadership Summit trains 15 members from each organization in advanced strategies for advocacy. Participants must be members of either the JACL or the OCA, and be nominated by their local chapters. Last year’s travel expenses were covered by the OCA, with a $150 fee going to cover the program expenses, as well as breakfast and lunch.
Celebrating AAPI Heritage Month
By: Wynton Yu
Tags: Racism, Politics, Activism, Asian American, Aapi Heritage Month

AAPI Heritage Month is coming to a close and so is the pandemic for that matter. It has definitely not been, if there ever was, an easy time to be Asian in America.

Last year, we were branded as the origin of the COVID virus- I recall a list of causes from a dirty wet market in Wuhan, where some guy ate a bat or a leakage at a bio-weapon lab. It didn’t matter anyways, people needed someone to blame and pointing fingers was easier than accepting responsibility for mishandling the outbreak.

Since then, our community has been under constant attack, first it was verbal abuse, then Asian-owned businesses were robbed and trashed, and finally the elderly were attacked in broad daylight. It became so common that the local Chinese evening news had at least one story as its opening headline every single day; Asians brutally beaten, set on fire, or robbed in their home. For the first time in almost 20 years, my family didn’t feel safe in our own house and my dad was convinced by his co-workers to place metal rods around the house in case we were attacked.

As many of my Asian friends know, the wider AAPI community (especially first generation-immigrants both old and new) have traditionally been conservative and detached from the political landscape. To put it simply, there’s a language and cultural barrier that leaves many households uninvolved in politics.

For many of us who have experienced discrimination in our lives, this battle is both external and internal. For a long time, a lot of us were complacent with racism and internalized lots of stereotypes into our cultural identity. We tolerated this problem until it grew into diabolical proportions that it finally threatened to dehumanize and take away our rights to exist.

However, rather than backing down and minding our own business as usual, we overthrew the mental shackles to speak up, to cry, to yell, and to fight. The AAPI community around the world faced the crisis in defiance with support from many other groups and movements. I saw friends and strangers from around the world join the conversation, Asian influencers and celebrities leverage their platform to raise awareness, and even my parents who have never once bothered with political activism came out to show support in a rally!

Mayor London Breed gives a speech at Union Square

I have never been more proud to be Asian and I believe that we must continue to take action so that we can leave a legacy and uphold a heritage for future generations to follow and take pride in.
My sketch of the world.
By: Dee Black Sheep
Tags: Stopasianhate, Anecdotes, Aapi, Asian American, American History

My sketch of the world.

We normally do not see maps with the Pacific Ocean as the center where Asia and the Americas are on either side, but this is my world. We may have different skin colors, speak different languages, and come from different parts of the world living on this planet. But one thing is the same; we are all human beings. Why must we see each other differently?

We live in America, a country famous for being a melting pot since its birth. Asians, Europeans, Africans, and other nationalities have come to look for better opportunities and have a better life. The promise of America: a land to seek refuge and everyone has equal access to the “American Dream.” We coexist and learn to share our cultures. We live in the same communities, go to the same schools, and hang out in the same coffee shops. Why are we always an outsider?

Today, there are about twenty-three million Asian Americans and we are the fastest growing ethnic group in the US. If we remain invisible, perhaps it is time to re-educate to bring about awareness and incorporate the facts about Asian Americans within American history.

- A Bay Area native looking for a belonging
“UX-ing” Asian Supermarket Websites
By: Tiffany Goh
Tags: Redesign, Supermarkets, Asian American, Website Design, UX Design

Photo from Unsplash by Fikri Rasyid

Growing up as an Asian American, I found myself shopping at Asian supermarkets more than my local grocery store. They sell the ingredients my parents would need to cook dishes they enjoyed growing up and often offer a cheaper and larger variety of fresh fruits and vegetables. It was difficult, and still can be difficult, to find the exact brand, sauce, or ingredient that we would need without a visit to an Asian supermarket to make the dish we had in mind — there are some things that you just can’t find in non-Asian supermarkets.

How does this relate to UX?

When COVID-19 hit, a large number of the Asian supermarkets in our area closed — we had to stock up on things that we needed beforehand, and hope that they would reopen soon.

You might be wondering, why don’t you just shop online on their website?

Most Asian supermarkets don’t have websites — in fact, only two Asian supermarket chains in the NYC area have websites for online shoppers.

When you Google one of the supermarkets with a website, you are directed to an English website where you can learn more about the supermarket, its story, its weekly deals, and locations. You are also informed that there is a separate site where you can purchase things online, but you would have to copy and paste the web address — there is no hyperlink to redirect you. You discover one issue when you land on the shopping site — everything is in Chinese and there’s no option to change it to English.

From a UX perspective, it would make more sense for the supermarket to combine the two sites, and prioritize the navigational items that are more important for the top navigation. It would even cost less money since they would only need to maintain and pay to host one website rather than two. They should also have the option to navigate the website in both English and Chinese — even better if there was the option to choose between traditional and simplified Chinese.

By making these small changes, a greater number of people would be able to shop at the supermarket virtually. It would also allow Asian Americans who can’t read Chinese well to buy ingredients from the supermarket online for themselves or their parents, so that they can avoid going out in crowds as the country reopens.
How Coaching Builds Asian Pacific American Leadership
By: Jess Ayden Li
Tags: Nonprofit, Coaching, Leadership Development, Asian American, Leadership

Some of the most successful individuals are those who work with coaches regularly. Just think about Steph Curry and Klay Thompson. They’re good basketball players, but they wouldn’t be as great at their game without Steve Kerr. So why aren’t more of us Asian Pacific American (APA) leaders using professional coaches, especially when it comes to our careers?

Earlier this year, I facilitated a workshop on salary negotiation and moving up the career ladder. I asked the group of APA professionals, “How many of you think that by just working hard, you’ll get a higher salary or a promotion?” I was surprised at the number of hands that went up. It was over 90% of the room. In the APA community, we often hear messages about needing to do well in school, going to college, and getting a good paying job. But only a few of us have grown up with messages related to job promotion or salary negotiations. I know I didn’t. In fact, my immigrant parents told me I should just be grateful that I have a steady job.

It wasn’t until I was in LEAP’s Executive Directors program that I had a coach for the first time. With his support, I became more confident in my role as an Executive Director. I learned how to better manage my staff. I understood how cultural issues affected decision making even within the same Asian community. I recognized how to leverage my soft skills to become a stronger leader.
spiraling
By: Faustina Ngo
Tags: Family, Asian American, Self-awareness

home.

things just keep happening, life keeps coming at me so fast and i don’t know what to do. why am i responsible for so many people’s feelings? i shouldn’t be responsible for their feelings,

why are you almost 60 years old and still bawling to me? why do i always have to be the grown-up for the both of us? is this manipulation or is it raw emotion? i don’t know which is which anymore. i’ve never known.. am i that heartless, to let the person who gave birth and raised me go into loneliness and sadness? or am i being strong and standing my ground, recognizing the patterns of control and breaking free?

but can i really blame myself though? did you set yourself up for that when you decided to cage me in, keep me from the world…for 18 years, until i finally ran away from your grasp?

i can't believe he's still under your hands. i hope he's doing okay.

i stay silent when friends or coworkers talk about their family, parents, siblings. i don’t have anything good to say.

i hate you. i hate you. i’ve said it so many times in my head. this is what i think when you ask me why i don't miss you or say “i love you” back. because i don't. i don’t. how could i?

but can i really blame you though? you were the oldest of 6 kids in vietnam, collecting scrap metal, selling banh mi from a street cart, doing everything you could to survive. you literally grew up in a war-torn country and you did the best you could…

i sympathize. i try to understand. but that doesn't cancel out the pain and harm you inflicted on the both of us. it’s unfair, i can’t just forgive you like that. i don't know if i ever could forgive you.