Euan M
0
Q:

javascript slice array

// array.slice(start, end)
const FRUITS = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = FRUITS.slice(1, 3);
// citrus => [ 'Orange', 'Lemon' ]

// Negative values slice in the opposite direction
var fromTheEnd = FRUITS.slice(-3, -1);
// fromTheEnd => [ 'Lemon', 'Apple' ]
24
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
// ["Orange", "Lemon"]
6
//The slice() method extracts a section of a string and returns 
//it as a new string, without modifying the original string.

// same in array but you select elements not characters  


const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// expected output: "the lazy dog."

console.log(str.slice(4, 19));
// expected output: "quick brown fox"

console.log(str.slice(-4));
// expected output: "dog."

console.log(str.slice(-9, -5));
// expected output: "lazy"

console.log(str.slice(0, 2)); 
// expected output: "the"
// Up to and including the last index!!!
// Different for python. 
16

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

var citrus = fruits.slice(1, 3);
 
3
//The slice() method extracts a section of a string and returns 
//it as a new string, without modifying the original string.

// same in array but you select elements not characters  


const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// expected output: "the lazy dog."

console.log(str.slice(4, 19));
// expected output: "quick brown fox"

console.log(str.slice(-4));
// expected output: "dog."

console.log(str.slice(-9, -5));
// expected output: "lazy"
7
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
// citrus value now is:  ["Orange","Lemon"]
3
function slice(array, start, end) {
    let a = [];
    let len = array.length;
    if (start < 0) start = len + start;
    if (end < 0) end = len + end;
    if (start < end) {
        for (let i = start; i < end; i++) {
            a.push(array[i]);
        }
    } else if (start === undefined && end !== undefined) {
        for (let i = end; i < len; i++) {
            a.push(array[i]);
        }
    } else if (end === undefined && start !== undefined) {
        for (let i = start; i < len; i++) {
            a.push(array[i]);
        }
    } else if (start > end || start === end) {
        return [];
    }
    return a;
}
-1

New to Communities?

Join the community