Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

slice method javascript

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

const objectArray = [
   {
      name: "Mehedi",
      age: 21
   },
   {
      name: "Ripon",
      age: 25
   },
   {
      name: "Developer",
      age: 22
   },
]

// only start index and it will slice the array from index 2
// upto last element of the array
const sliceStart = array.slice(2)

// start and end index
const sliceStartEnd = array.slice(2, 4)

// negative index
const negativeSlice = array.slice(-2)

// negative end index with positive start index
const negativeSliceStartEnd = array.slice(1, -2)

//slice chaining
const sliceChaining = array.slice(2, 4).slice(0, 4)

// slicing object array
const objectArraySlicing = objectArray.slice(1, 3)

// slicing the first half of the array excluding the middle element
const lengthSlicing = array.slice(Math.floor(array.length / 2), array.length)

// slice then sort in descending order
const sliceSort = array.slice(2, 5).sort((a, b) => b - a)

// slice then filter
const sliceFilter = array.slice(2, 6).filter(i => i > 4)

// slice then map
const sliceMap = array.slice(2, 5).map(i => i * 4)

// returning an array after slicing  
const restParameters = (args) => {
   return args.slice(2, 6)
}

console.log("Slicing with only start index - ", sliceStart)
console.log("Slicing with start and end index - ", sliceStartEnd)
console.log("Slicing with negative index - ", negativeSlice)
console.log("Slicing with negative end index - ", negativeSliceStartEnd)
console.log("Slicing with chaining - ", sliceChaining)
console.log("Slicing with array of objects - ", objectArraySlicing)
console.log("Slicing the second half of the array - ", lengthSlicing)
console.log("Slicing with sort - ", sliceSort)
console.log("Slicing with filter - ", sliceFilter)
console.log("Slicing with map - ", sliceMap)
console.log("Slicing array inside function - ", restParameters(array))
Source by dev.to #
 
PREVIOUS NEXT
Tagged: #slice #method #javascript
ADD COMMENT
Topic
Name
9+9 =