Useful Array functions

6 0 0
                                        

1. splice(start, total number to delete, add1 ... addN)

     - it will delete elements from the start until the end depending on the setting of the total number to delete. And you have the options to add elements or not. If you won't add elements, that means you just want to cut it or delete some elements. Note that this function returns a new array

===================

let array = [1, 2, 3];

function practicingArray(){

     let list1 = array.splice(0, 3, "apple", "banana", "chery");

    document.writeln(list1)

    document.writeln(array);

}

===================

HTML

practicingArray()

Result:

1,2,3 apple,banana,chery

Note: In the program, list1 should be first and the array is the last to be displayed. But what happens was the opposite.

2. slice(start, end)

     - it copies the elements from the start until before the end. Note that it returns a new array.

===================

let array = [1, 2, 3];

function practicingArray(){

    let list1 = array.splice(0, 3, "apple", "banana", "chery");

    let list2 = array.slice(0, 2);

    document.writeln(list1);

    document.writeln(list2);

    document.writeln(array);

}

===================

HTML

practicingArray()

Result:

1,2,3 apple,banana apple,banana,chery

Note: array displayed first. Then list2 displayed second. And last is the list1.

3. concat(add1 ... addN)

    - use concat if you want to add something in the array but note that this returns a new array.

    concat(object)

    - you can add an object but make sure that key name is in numeric form. This doesn't mean that the type is Number but make sure that compiler can infer it to be in a Number type or else it won't be included in the return types. Also, you need to add [Symbol.isConcatSpreadable] as a key with a value of true. Also, add the length as key with a value that will determine the number of elements you want to add in you array.

======================

let array = [1, 2, 3];

let object1 = {

    0: "green",

    1: "heaven",

    2: "india",

    3: "joker",

    [Symbol.isConcatSpreadable]: true,

    length: 4

Javascript ProgrammingWhere stories live. Discover now