Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
What are possible ways of assigning an array's first and last item as well as the array of items in between each to a separate variable?

let's say I have the following data array

["New York", "Madrid", "Roma"]

And I have 2 other variables and another array

firstValue = '';
middlesValues = []
lastValue = ''

output

firstValue = 'New York'
middlesValues = ['Madrid']
lastValue = 'Roma'

And I would like for example to put the first value in the array each time in a variable, the middle values in an array and the last value in the last variable. And if I have only two values in the array, to put only the first value and the last one in the 2 variables.

How can I proceed.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use array.slice to get the subarray, returns an empty array if you only have 2 elements.

const array= ["New York", "Madrid", "Roma"];

const firstValue = array[0];
const middlesValues = array.slice(1, array.length - 1);
const lastValue = array[array.length - 1];

console.log(firstValue);
console.log(middlesValues);
console.log(lastValue);

about 4 years ago · Juan Pablo Isaza Relatório

0

Use Array#shift to get the first element, Array#pop to get the last, and the rest would be the middle ones:

const partition = (arr = []) => {
  const array = [...arr];

  const firstValue = array.shift();
  const lastValue = array.pop();
  const middlesValues = array;

  return { firstValue, middlesValues, lastValue};
}

console.log( partition(["New York", "Madrid", "Boston", "Roma"]) );
console.log( partition(["New York", "Madrid", "Roma"]) );
console.log( partition(["New York", "Madrid"]) );
console.log( partition(["New York"]) );
console.log( partition([]) );

about 4 years ago · Juan Pablo Isaza Relatório

0

The approach depends on whether the OP wants the original data to be mutated or not.

The shortest non mutating way is to use a combination of array destructuring and pop ...

let [firstValue, ...middlesValues] = array;
let lastValue = middlesValues.pop();

possible approaches could be ...

// - approach does not mutate the original data.
// - it does so by using array destructuring and `pop`.
let sampleData = ["New York", "Madrid", "Roma", "Paris"];

let [firstValue, ...middlesValues] = sampleData;
let lastValue = middlesValues.pop();

console.log({ firstValue, lastValue, middlesValues, sampleData });

sampleData = ["New York", "Madrid"];

[firstValue, ...middlesValues] = sampleData;
lastValue = middlesValues.pop();

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log('\n');


// - approach does not mutate the original data.
// - it does so by uitlizing `at` and `slice`.
sampleData = ["New York", "Madrid", "Roma", "Paris"];

firstValue = sampleData.at(0);
lastValue = sampleData.at(-1);
middlesValues = sampleData.slice(1, -1);

console.log({ firstValue, lastValue, middlesValues, sampleData });

sampleData = ["New York", "Madrid"];

firstValue = sampleData.at(0);
lastValue = sampleData.at(-1);
middlesValues = sampleData.slice(1, -1);

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log('\n');


// - approach does mutate the original data.
// - it does so by by choosing the proven way of `shift` and `pop`.
sampleData = ["New York", "Madrid", "Roma", "Paris"];

firstValue = sampleData.shift();
lastValue = sampleData.pop();
middlesValues = sampleData;

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log(
  '(middlesValues === sampleData) ?..',
  (middlesValues === sampleData)
);
sampleData = ["New York", "Madrid"];

firstValue = sampleData.shift();
lastValue = sampleData.pop();
middlesValues = sampleData;

console.log({ firstValue, lastValue, middlesValues, sampleData });
console.log(
  '(middlesValues === sampleData) ?..',
  (middlesValues === sampleData)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda