How Does is Turn a Pseudo Array Into A True Array?

How Does is Turn a Pseudo Array Into A True Array?

How does js turn a pseudo array into a true array? The following article introduces three methods for turning a pseudo array into a true array.

How does js turn a pseudo array into a true array? The following article introduces three methods for turning a pseudo array into a true array. There is a certain reference value, friends in need can refer to it, I hope to help everyone.

The first thing to know is what is a pseudo array?
Pseudo-arrays are objects like arrays, for example:

obj = {
    "0": "zhang",
    "1": 18,
    length: 2
}

This is a pseudo array, which contains the length property

So how to turn a pseudo array into a true array?

1. 1. []. Slice.call (obj) This is equal to Array.protype.slice.call (obj)

The slice will get the new array through the index position. This method will not modify the original array, but just returns a new sub-array. The call will change the pointing of this to the passed obj

var newArr = []. slice.call (obj)
2. Array.form (obj), ES6's new syntax
var newArr = Array.from (obj)
3.Use extension operators, which is also ES6 syntax
var newArr = [... obj]

JavaScript Array.flatMap()

JavaScript Array.flatMap()

JavaScript Array.flatMap(): Use flatMap to map over an array and flatten the result array in one go! Now lets up the game and introduce "flatMap". It combines the steps of first mapping over the array with `map()` & then calling `flat()`. Instead of calling 2 methods, just use `flatMap()` πŸ‘

Now lets up the game and introduce "flatMap". It combines the steps of first mapping over the array with map() & then calling flat(). Instead of calling 2 methods, just use flatMap() πŸ‘

const foods = ['🍫', '🍦'];

// ❌ map + flat
foods.map(food => [food, 'πŸ˜‹']).flat();

// βœ… flatMap
foods.flatMap(food => [food, 'πŸ˜‹']);

// Result
// ['🍫', 'πŸ˜‹', '🍦', 'πŸ˜‹']

How flatMap() works?

Let's go through step-by-step what flatMap() is doing. I was a bit confused when I first learned this one. Cause I thought it flattens and then it does the mapping. But no πŸ™…. It first map() and then it flat().

const names = ['jane', 'john'];

// Step 1: map
const nestedArray = names.map((name, index) => [name, index]);
// [ ['jane', 1], ['john', 2 ] ]

So now we have a nested array. And we can use flat() to flatten the array.

const nestedArray = [
  ['jane', 1],
  ['john', 2]
];

nestedArray.flat();
// [ 'jane', 1, 'john', 2 ]

Of course, we can shorten this and just call flatMap(). Let's take a look πŸ‘€

const names = ['jane', 'john'];

const result = names.flatMap((name, index) => [name, index]);

// [ 'jane', 1, 'john', 2 ]

And Voila! We have the same result πŸ‘

flatMap only flattens 1-level deep

With flat(), it accepts a parameter where you set the depth. What this means is you can specify how deep a nested array should be flattened.

const depth1 = [[1], [2]];
depth1.flat(); // same as depth.flat(1)
// [1, 2]

const depth2 = [[[1, 2]]];
depth2.flat(2);
// [1, 2]

Now for flatMap(), you can only go 1-level deep.

const names = ['jane'];

names.flatMap((name, index) => [[name, index]]);
//  [ ['jane', 1] ]

Let's break this into 2 steps, so you can see what's going on.

const names = ['jane'];

// Step 1: created a 2-level deep array
const twoLevelDeep = names.map((name, index) => [[name, index]]);
// [ [ ['jane', 1] ] ]

// Step 2: flat using depth 1
twoLevelDeep.flat();
//  [ ['jane', 1] ]

But if you do it separately, I can pass a depth parameter and flatten it completely:

twoLevelDeep.flat(2);
// [ 'jane', 0, 'john', 1 ]

So, if you want it to flatten beyond depth of 1. Then it is better to NOT use flatMap() and just call the methods separately πŸ‘

flatMap to filter item

One really cool you can do with flatMap is to remove an element. In this example, I want to remove all negative numbers.

const numbers = [1, 2, -3, -4, 5];

numbers.flatMap(number => {
  return number < 0 ? [] : [number];
});

// [ 1, 2, 5]

That's really cool! It's like acting like a filter. But how is this actually working. The secret is the empty array. Let's see what I mean.

const emptyNestedArray = [[], 1];

emptyNestedArray.flat();
// [ 1 ]

When you try to flatten an element that's an empty array, it simply removes that item. So we can use that knowledge to make flatMap act kind of like filter method. Neat right! πŸ‘

Resources

Originally published at https://www.samanthaming.com

JavaScript array : How to merge two arrays in JavaScript

JavaScript array : How to merge two arrays in JavaScript

In this post, We go over how to merge two arrays in JavaScript using the concat method and the spread syntax.

Array Concat() method

The concat method is used to merge two arrays. As a result, it returns a new array instead of modifying the existing array.

Let’s look at an example using the concat method. We have two arrays named fruits1 and fruits2. They both contain strings that correspond to a fruit.

const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = fruits1.concat(fruits2);

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]


Array Spread syntax

Now let’s look at an example using the spread syntax.


const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = [...fruits1, ...fruits2];

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]

In this example, we created a new array and assigned it to the variable combinedFruits. We then took the two fruits array and used the spread them out in the array. We used the ... syntax to spread out the contents of the fruits array into the new array.

Thanks for reading !

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.