For loop only gives the last value of an array

I've been trying to transpose a matrix (-like 2D array) in ES6 but the for loop only gives the last value of the original array and I have no idea what I did wrong.

I've been trying to transpose a matrix (-like 2D array) in ES6 but the for loop only gives the last value of the original array and I have no idea what I did wrong.

Suppose the size of the spectrum array is 128 x 128:

const width = 128;
const height = 128;

var spectrum: Complex[][] = fft(data);

// Transpose spectrum array
var transposedData: Complex[][] = new Array(height).fill(new Array(width));
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const c = spectrum[x][y].deepCopy();
transposedData[y][x] = c;
}
}

spectrum = transposedData;
console.log(spectrum);

This gives me a 2D array, every element of which is the value of spectrum[127][127]. What have I done wrong?

Introduction Boolean in JavaScript and TypeScript

Introduction Boolean in JavaScript and TypeScript

Boolean values are supported by both JavaScript and TypeScript and stored as true/false values .This is because, while JavaScript coerces an object to its primitive type, the TypeScript type system does not. TypeScript treats it like an object type.

Boolean in JavaScript

boolean can take the values of true and false. Values from other types can be truthy or falsy, like undefined or null.

let b = true
if(b) console.log('logged')

b = false
if(b) console.log('not logged')

b = undefined
if(b) console.log('not logged')

b = null
if(b) console.log('not logged')

Values other than undefined, null or false considered falsy are "" (empty string), -0 and 0, as well as NaN.

To get the boolean value of any value, you can use the Boolean function:

Boolean(false) // false
Boolean(true) // true
Boolean("false") // true ❗️
Boolean("Hey folks") // true
Boolean({}) // true
Boolean([]) // true
Boolean(123.4) // true
Boolean(Symbol()) // true
Boolean(function() {}) // true
Boolean(undefined) // false
Boolean(null) // false
Boolean(NaN) // false
Boolean(0) // false
Boolean("") // false

Rule of thumb: All empty values evaluate to false. Empty object {} and empty array [] (which is an object itself) do have value as they are containers for other values.

The Boolean function is really good to filter empty values from collections:

const collection = [
  { name: 'Stefan Baumgartner', age: 37 },
  undefined,
  { name: 'D.', age: 36 },
  false
  { name: 'C.', age: 2},
  false
]

collection.filter(Boolean) // handy!

Together with Number – which converts all values into their number counterpart or NaN, this is a really cool way of getting to actual values quickly:

const x = ["1.23", 2137123, "wut", false, "lol", undefined, null]
  .map(Number)
  .filter(Boolean) // [1.23, 2137123] πŸ‘

Boolean exists as a constructor and has the same conversion rules as the Boolean function. However, with new Boolean(...) you create a wrapping object, making value comparisions truthy, but reference comparisions falsy:

const value = Boolean("Stefan") // true
const reference = new Boolean("Stefan") // [Boolean: true]

value == reference // true
value === reference // false

You get to the value via .valueOf():

value === reference.valueOf() // true

I have a REPL for you to check. The use of Boolean as a function is obviously great, but new Boolean has very limited use. If you know a practical use case, please let me know.

Boolean in TypeScript

boolean in TypeScript is a primitive type. Be sure to use the lower case version and don’t refer to
object instances from Boolean

const boolLiteral: boolean = false // πŸ‘
const boolObject: Boolean = false // πŸ‘Ž

It works, but it’s bad practice as we really rarely need new Boolean objects.

You can assign true, false and undefined and null to boolean in TypeScript without strict null checks.

const boolTrue: boolean = true // πŸ‘
const boolFalse: boolean = false // πŸ‘
const boolUndefined: boolean = undefined // πŸ‘
const boolNull: boolean = null // πŸ‘

With that, boolean is the only one we can express fully through union types:

type MyBoolean = true | false | null | undefined // same as boolean

const mybool: MyBoolean = true
const yourbool: boolean = false

When we enable the strictNullChecks compiler flag, the set of values reduces to true and false.

const boolTrue: boolean = true // πŸ‘
const boolFalse: boolean = false // πŸ‘
const boolUndefined: boolean = undefined // πŸ’₯
const boolNull: boolean = null // πŸ’₯

So our set reduces to two values in total.

type MyStrictBoolean = true | false

We can also get rid of null values with the NonNullable helper type:

type NonNullable<T> = T extends null | undefined
  ? never
  : T;

type MyStrictBoolean = NonNullable<MyBoolean> // true | false

The fact that boolean consists of a limited set of values only used in conditions, allows for interesting conditional types.

Think of an mutation in a datastore through a function. You set a flag in a function that updates e.g. the user id. You have to provide the user ID then:

type CheckUserId<Properties, AddUserId> = 
    AddUserId extends true 
    ? Properties & { userId: string }
    : Properties & { userId?: string }

Depending on the value of our generic AddUserId, we expect the property userId to be set or to be optional.

We can make this type more explicit by extending our generics from the types we expect

- type CheckUserId<Properties, AddUserId> = 
+ type CheckuserId<
+  Properties extends {},
+  AddUserId extends boolean
+ >
     AddUserId extends true 
     ? Properties & { userId: string }
     : Properties & { userId?: string }

In use, it might declare a function like this:

declare function mutate<P, A extends boolean = false>
  (props: CheckUserId<P, A>, addUserId?: A): void

Note that I even set a default value for A to make sure CheckUserId gives the correct info depending on addUserId to be set or not.

The function in action:

mutate({}) // πŸ‘
mutate({ data: 'Hello folks' }) // πŸ‘
mutate({ name: 'Stefan' }, false) // πŸ‘
mutate({ name: 'Stefan' }, true) // πŸ’₯ userId is missing
mutate({ name: 'Stefan', userId: 'asdf' }, true) // πŸ‘ userId is here

Handy if your code relies a lot on truthy and falsy values. As always, there’s playground for you.

Originally published at fettblog.eu on 10 September 2019

All about JavaScript Arrays Methods

All about JavaScript Arrays Methods

Everything You Need to Know About JavaScript Array Methods

Web development or web programming gave birth to dynamic web applications. With the rise of the web, JavaScript has become one of the most important languages in today’s world. This **JavaScript Array **article will take you to the depths of array methods in JavaScript in the following sequence:

  • Introduction to JavaScript
  • Fundamentals of JavaScript
  • JavaScript Array
  • Difference between Array and Objects
  • JavaScript Array Methods
Introduction to JavaScript

JavaScript is a high level, interpreted, programming language used to make web pages more interactive. It is a very powerful client-side scripting language which makes your webpage more lively and interactive.

It is a programming language that helps you to implement a complex and beautiful design on web pages. If you want your web page to look alive and do a lot more than just gawk at you, JavaScript is a must.

Fundamentals of JavaScript

If you are new to the language, you need to know some of the fundamentals of JavaScript that will help you start writing your code. The basics include:

JavaScript Array

An array is a data structure that contains a list of elements which store multiple values under a single variable.

To declare an array in JavaScript use the β€˜let’ keyword with square brackets and enclose all the elements within them. The syntax is as follows:

let ListItems=[];
ListItems=['shoes','watch','bag'];

You can also declare it as:

let ListItems=['shoes','watch','bag'];

Difference between Array and Objects

JavaScript variables can be objects. Arrays are considered to be special kinds of objects. Because of this, you can have variables of different types in the same Array.

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myItems;

In JavaScript, arrays use numbered indexes. Whereas, objects are used as named indexes.

JavaScript Array Methods

The purpose of using an array is to store** multiple values** in a single entity of a declared variable. Arrays are used when we want to access elements in an orderly fashion using a single variable. One can store strings, boolean and numbers in a single array.

There are different JavaScript array methods in order to perform various tasks such as:
push() – It is easy to remove elements and add new elements while working with arrays. The push() method adds a new element to the end of an array. The return value is the new array length.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.push('watch'));

Output:

4

Push() doest not return the value that has been added to the array. It only returns the new length of the array.
**pop() – **The pop() method is used to remove the last element from an array. It returns the value that has been popped out.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.pop());

Output:

dress

Pop() returns the value that has been removed and not the array length like Push().
shift() – Shifting is similar to popping, working on the first element instead of the last. The shift() method is used to remove the first array element and shifts all other elements to a lower index. It will return you the string that has been shifted out.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.shift());

Output:

bag

Shift() works same as pop() but it returns the first element of the array instead of the last one.
unshift() – The unshift() method adds a new element at the beginning of an array and unshifts older elements. It is similar to Push() and returns the new array length.
**Example: **

let listItems = ['bag','shoes','dress','watch'];
console.log(listItems.unshift('phone'));

Output:

5

Unshift() will add the new element into the array and return the length of the new array.
concat() – The concat() method creates a new array by concatenating or merging existing arrays. It does not modify the existing array and always returns a new array.
Example:

let arr1 = ['red','blue','green'];
let arr2 = ['colors','spraypaint', 'brush'];
let newArr = arr1.concat(arr2);
console.log(newArr);

Output:


toString() – The toString() method is used to convert an array to a string of array values, separated by commas.
Example:

let colors = ['red','blue','green'];
console.log(colors.toString());

Output:

red,blue,green

join() – The join() method works same as toString(). It is used to join all array elements into a string, but in addition, you can specify the separator.
Example:

let colors = ['red','blue','green'];
console.log(colors.join("+"));

Output:

red+blue+green

reverse() – The reverse() method is used to reverse the order of the elements in an array. It will change the original array and swap the order of the elements.
Example:

let fruits = ['mango','apple','grapes'];
console.log(fruits.reverse());

Output:


sort() – The sort() method is used to sort an array alphabetically. This function sorts the values as string by default.
Example:

let fruits = ['mango','apple','grapes'];
console.log(fruits.sort());

Output:


slice() – The slice() method is used to slice out a piece of an array into a new array. It creates a new array without removing any elements from the source array. It will return the value that has been sliced out from the array.
Example:

let colors = ['red','blue','green','yellow','orange'];
console.log(colors.slice(1,3));

Output:

These were some of the most commonly used JavaScript array methods. With this, we have come to the end of our article. I hope you understood how array methods are used in JavaScript.

How to reverse an array in JavaScript?

How to reverse an array in JavaScript?

Here's a Code Recipe to keep around if you need to reverse the order of the elements of an array. You can use the array method, "reverse()" βͺ

Trying a new segment called #CodeRecipes. I want to cover questions that I often google. These are recipes that you should definitely keep handy because it's not a matter "if" you use it, but "when" πŸ˜‰

const benjamin = ['πŸ‘Ά','πŸ‘¦', 'πŸ‘¨', 'πŸ‘΄'];

const benjaminButton = benjamin.reverse();

console.log(benjaminButton);
// ['πŸ‘΄', 'πŸ‘¨', 'πŸ‘¦', 'πŸ‘Ά']

Modifies Original Array

One thing to note is that it mutates the original array.

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reverse();

console.log(originalArray); // [ 'c', 'b', 'a' ]
console.log(newArray); // [ 'c', 'b', 'a' ]

How to Reverse Array Without Mutating Original Array

Here are some recipes that won't mutate the original array. Let's take a look πŸ‘€

Using slice and reverse

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.slice().reverse();

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using spread and reverse

const originalArray = ['a', 'b', 'c'];
const newArray = [...originalArray].reverse();

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using reduce and spread

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduce((accumulator, value) => {
  return [value, ...accumulator]
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using reduceRight and spread

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
  console.log(value);
  return [...accumulator, value]
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Or using push

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
  accumulator.push(value);
  return accumulator;
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Source code and tests are available here

Resources