Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.pop - last two elements - JavaScript

I have a question using Array.pop function in JavaScript. Array.pop removes and returns the last element of an Array. My question is then: is it possible to remove and return the last TWO elements of array and return them instead of the last?

I am using this function to return the last element of URL, like this:

URL: www.example.com/products/cream/handcreamproduct1

'url'.splice("/").pop(); -----> "handcreamproduct1"

what i want is:

'url'.splice("/").pop(); -----> "cream/handcreamproduct1"

I want to take the last two parameters in the url and return them, with .pop i only get the last one. Remember that the URL is dynamic length. The url can look like this:

URL: www.example.com/products/cream/handcreamproduct1
OR
URL: www.example.com/products/handcream/cream/handcreamproduct1

like image 760
Asim Avatar asked Oct 16 '17 07:10

Asim


3 Answers

Split the array, use Array#slice to get the last two elements, and then Array#join with slashes:

var url = 'www.example.com/products/cream/handcreamproduct1';

var lastTWo = url
  .split("/") // split to an array
  .slice(-2) // take the two last elements
  .join('/') // join back to a string;

console.log(lastTWo);
like image 64
Ori Drori Avatar answered Oct 19 '22 23:10

Ori Drori


I love the new array methods like filter so there is a demo with using this

let o = 'www.example.com/products/cream/handcreamproduct1'.split('/').filter(function(elm, i, arr){
    if(i>arr.length-3){
  return elm;
  }
});
console.log(o);
like image 36
Álvaro Touzón Avatar answered Oct 20 '22 01:10

Álvaro Touzón


There is no built in array function to do that.

Instead use

const urlParts = 'url'.split('/');
return urlParts[urlParts.length - 2] + "/" + urlParts[urlParts.length - 1];
like image 1
klugjo Avatar answered Oct 20 '22 01:10

klugjo