How to manipulate array of objects in Javascript?

In Javascript, we often need to manipulate array objects. This post mainly introduces: ① How to get the index of array elements? ② How to delete array elements? ③ How to slice array elements? ④ How to insert elements in the array? ⑤ How to concat arraies?

Keywords: Javascript , array , indexOf , delete , slice , insert.

IndexOf

Sometimes we need to get the index of an array element. In this case, we can use the indexOf() method. If no element is found, the function returns -1. It should be noted that if the array or object is stored in the array, the returned result of indexOf() will always be -1. It is necessary to compare the sub-objects in the elements one by one to see if they are equal to obtain the index. Or you can use JSON.stringify() methond to compare two object, but if the order of object key are need to be consistent, otherwise, you will always get False even compare two same object.

Delete

When deleting elements from an array, you can use the splice(start_index, count) function, where start_index indicates the position where the start index, and count indicates how many elements to delete from start_index.

Slice

Use slice(start_index, end_index) function when intercepting elements of an array.

Insert

To insert element in an array, you can use the unshift() or push() methods. The unshift() method inserts element at the beginning of array, and the push() method inserts element at the end.

Concat

If you want to concat two arraies, there are concat(), apply(), push() and for..loop methods.

In Javascript, we can use indexOf() to get element index,use splice() to remove element,use unshift() and push() to insert element, use concat(), apply() and for…loop to concatenate arrays.

Edit Template

Leave a Reply

Your email address will not be published. Required fields are marked *

Chaoxu Wei

Master student at Tongji University (Writer & Blogger)

Job hunting, both part-time and full-time jobs are accepted. Job recommendation please email me weichaoxu1998@gmail.com, thank you very much!

0
0
Edit Template

“There are many people in the world who want to work hard but can’t, and people who work too hard and are exhausted. Please don’t use your efforts only to chase your own victory, please use them to help others.”

Follow

Contact

libertynlp@163.com

+86-18385537403

Yangpu District, Shanghai