I have wandered around a few IT blogs, I have picked up some pretty good tips array(Array)
in Javascript
, want to share them again. And if anyone knows of any other tips, please share with her for us to improve the knowledge to work with Array
Let’s start with us!
This is a very common interview question about Array Javascript
, how to extract unique values in Array. Solve this problem, you can use new Set()
.
let fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
// First method
let uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits); // returns ['banana', 'apple', 'orange', 'watermelon', 'grape']
// Or use Second metho
let uniqueFruits2 = [...new Set(fruits)];
console.log(uniqueFruits2); // returns ['banana', 'apple', 'orange', 'watermelon', 'grape']
Sometimes, you need to replace a specific value in an array and have a good, concise method to do that. We can use the splice()
method.
Syntax: Array.splice(index, howmany, item1, ..., itemX)
Inside:
index
- is the replacement starting position.howmany
- the number of elements to be removed, from the position index
including the index element. If howmany
the value is 0 then no elements will be removed.item1, ..., itemX
- elements will be added from the position index
. After adding, the indexed index of the array will be item1.let fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple'];
fruits.splice(0, 2, 'potato', 'tomato');
console.log(fruits); // returns ['potato', 'tomato', 'orange', 'watermelon', 'apple']
Perhaps everyone knows the map()
method in Array, but there is another solution used that has the same result and the code is quite clean. That is, we can use the from()
method for this purpose.
let friends = [
{ name: 'John', age: 22 },
{ name: 'Peter', age: 23 },
{ name: 'Mark', age: 24 },
{ name: 'Maria', age: 22 },
{ name: 'Monica', age: 21 },
{ name: 'Martha', age: 19 },
];
// Use Array.from()
let friendsNames = Array.from(friends, ({name}) => name);
console.log(friendsNames); // returns ['John', 'Peter', 'Mark', 'Maria', 'Monica', 'Martha']
// Use Array.map()
let friendsNames2 = friends.map((friend, index) => {
return friend.name;
});
console.log(friendsNames2); // returns ['John', 'Peter', 'Mark', 'Maria', 'Monica', 'Martha']
The fairly simple way, you just need to assign Array.length = 0
that everything is solved. There are also other ways, let’s see an example.
let fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
fruits.length = 0;
// or
fruits = [];
// or
fruits.splice(0);
// or
while (fruits.length > 0) {
fruits.pop();
}
console.log(fruits); // returns []
This problem happens that we have an Array array, but for some purpose, we need to convert it into an Object with that data. The fastest way to convert an Array array to an Object is to use Spread Operator (...)
in ES6
.
let fruits = ['banana', 'apple', 'orange', 'watermelon'];
let fruitsObj = { ...fruits };
console.log(fruitsObj); // returns {0: 'banana', 1: 'apple', 2: 'orange', 3: 'watermelon'}
With this problem, we will immediately think about using methods concat()
. We can also solve by re-using Spread Operator (...)
in again ES6
.
let fruits = ['apple', 'banana', 'orange'];
let meats = ['poultry', 'beef', 'fish'];
let vegetables = ['potato', 'tomato', 'cucumber'];
// Use Spread Operator ES6
let foods = [...fruits, ...meats, ...vegetables];
console.log(foods); // returns ['apple', 'banana', 'orange', 'poultry', 'beef', 'fish', 'potato', 'tomato', 'cucumber'];
// Use concat() method
let foods2 = fruits.concat(meats, vegetables);
console.log(foods2); // returns ['apple', 'banana', 'orange', 'poultry', 'beef', 'fish', 'potato', 'tomato', 'cucumber'];
The problem that assumes this section is to find common values between two arrays and that they cannot be duplicated.
let numOne = [0, 2, 4, 6, 8, 8];
let numTwo = [1, 2, 3, 4, 5, 6];
// Use include() method
let duplicatedValues = [...new Set(numOne)].filter(item => numTwo.includes(item));
console.log(duplicatedValues); // returns [2, 4, 6]
// Use has() method
let firstValues = new Set(numOne);
let duplicatedValues2 = numTwo.filter(item => firstValues.has(item));
console.log(duplicatedValues2); // returns [2, 4, 6]
First, to determine the value Falsy
, you can find more reading here . In Javascript
, whose values Falsy
are false, 0 hoặc NaN, '' hoặc "", null, undefined
.
Now, we can learn how to remove this value from the array. To achieve this, we will use the methodfilter()
let mixedArr = [0, 'blue', '', NaN, 9, true, undefined, 'white', false, "", null];
let trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // returns ['blue', 9, true, 'white']
The problem is that we have an Array array and have duplicate values, find the position that appears last. Solve problems using methods lastIndexOf()
.
let nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7];
let lastIndex = nums.lastIndexOf(5);
console.log(lastIndex); // returns 9
This we can use for()
or foreach()
, declare a variable sum
and then add each value in the array. With ES6, we have a method reduce()
for making the calculation short and clean.
let numbers = [5, 15, 20];
let sum = numbers.reduce(function(a, b) {
return a + b;
});
let sub = numbers.reduce((a, b) => {
return a - b;
});
let mul = numbers.reduce((a, b) => {
return a * b;
});
let div = numbers.reduce((a, b) => {
return a / b;
});
console.log(sum); // 40
console.log(sub); // -30
console.log(mul); // 1500
console.log(div); // 0.016666666666666666
When we need to reverse the array, there’s no need to create it through complex loops and functions. Let’s use the reverse()
easy method that does it all for us.
let colors = ['white', 'green', 'navy', 'pink', 'purple'];
let reversedColors = colors.reverse();
console.log(reversedColors); // returns ['purple', 'pink', 'navy', 'green', 'white']
console.log(colors); // returns ['purple', 'pink', 'navy', 'green', 'white']
With the above usage, the original array colors[]
will also be changed accordingly. If you don’t want to change its original array, you can write:
let colors = ['white', 'green', 'navy', 'pink', 'purple'];
let reversedColors = [...colors].reverse();
// or
let reversedColors2 = colors.slice().reverse();
console.log(colors); // returns ['purple', 'pink', 'navy', 'green', 'white']
console.log(reversedColors); // returns ['purple', 'pink', 'navy', 'green', 'white']
console.log(reversedColors2); // returns ['purple', 'pink', 'navy', 'green', 'white']
Use method Math.min()
let numbers = [80, 300, 1500];
let min = Math.min(...numbers);
// Or
let min = Math.min.apply(null, numbers);
console.log(min); // 80
In this article, I have shared with you a few tips I know. Hopefully the above tips will help you a lot while working with Javascript.
Thank you for reading my article!
#javascript #programming