Q: Best way to get as output an array with the first word in position 0 and others in position 1? I need to know if I can make this code better and faster.
Example Input: 
"hi my name is john cena"

Expected Output: 
["hi", "my name is john cena"]

My code:
function getParams(query) {
    var keys = query.split(' ');
    var params = [];
    if(keys.length >= 2) {
        params.push(keys[0]);
        params.push("");
        for(var i = 1; i<=keys.length - 1; i++) {
            if(i != keys.length - 1) {     
                params[1] += keys[i] + " ";  
            }  else { 
                params[1] += keys[i];
            }
        }
    }
    return params;
}


A: You can use the magic of rest/spread syntax, to construct your desired result array:
function getParams(query) {
  let [first, ...rest] = query.split(" ");
  return [first, rest.join(" ")];
}

Explanation:


*

*In the following code first will hold the first element from the
resulting array of query.split(" ") and rest will hold the remaining
words/elements of it.

*Then we return an array which contains first and the rest array
joined as a string using rest.join(" ") to get the desired
original remaining part of the query string.


Demo:


let str = "hi my name is john cena";

function getParams(query) {
  let [first, ...rest] = query.split(" ");
  return [first, rest.join(" ")];
}

console.log(getParams(str));



A: The Array.slice method is very helpful here.
function getParams(x) {
    const index = x.indexOf(' ')
    return [x.slice(0, index), x.slice(index + 1)]
}


A: 

var text = "hi my name is john cena";

function getParams(query) {
  var idx = query.indexOf(' ');
  return [ query.substr(0, idx), query.substr(idx + 1) ];
};

console.log(getParams(text));


Hope this helps you

A: You can simply split the string in two parts based on the first occurrence of white space:


let str = "hi my name is john cena";
let result = str.split(/\s(.+)/);
result.pop()
console.log(result);


