Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Matriz JavaScript de objeto: grupo si el valor después de otro es el mismo

Necesito agrupar elementos de matriz, si son iguales. Pero sólo, si siguen después de otro.

Los elementos individuales sin el mismo valor antes o después deben ignorarse.

Ejemplo:

 const array = [ {country : 'usa', continent: 'north america'}, {country : 'germany', continent: 'europe'}, {country : 'france', continent: 'europe'}, {country : 'india', continent: 'asia'}, {country : 'netherlands', continent: 'europe'}, ]

El resultado debería ser:

 [ {country : 'usa', continent: 'north america'}, [ {country : 'germany', continent: 'europe'}, {country : 'france', continent: 'europe'} ], {country : 'india', continent: 'asia'}, {country : 'netherlands', continent: 'europe'}, ] ]

Esta solución también funcionaría:

 [ {country : 'usa', continent: 'north america'}, {grouped: 'continent', countries: [ {country : 'germany', continent: 'europe'}, {country : 'france', continent: 'europe'} ] }, {country : 'india', continent: 'asia'}, {country : 'netherlands', continent: 'europe'}, ] ]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Dado que tiene la condición de que dos países se agrupen en el mismo continente, deben ser hermanos adyacentes, la forma más rápida de producir ese resultado y visitar la matriz de entrada solo una vez es realizar un seguimiento del continente anterior y llenar una cola de países para impulsar la salida de una sola vez cuando el siguiente país de entrada rompe la cadena.

Esta demostración generará en la consola la matriz de resultados creada como se describe anteriormente:

 const array = [ {country : 'usa', continent: 'north america'}, {country : 'germany', continent: 'europe'}, {country : 'france', continent: 'europe'}, {country : 'india', continent: 'asia'}, {country : 'netherlands', continent: 'europe'}, ]; function flushQueue(queue, destination, useWrapper = false){ //if the queue has more than one country if(queue.length > 1){ //if useWrapper was passed to the function as true if (useWrapper){ //overwrites queue with the new wrapper object queue = { //the continent property is picked by the first item in the queue //there's no need to check any other coming next, because anyway //they would be sharing all the same value. The first item will //exist for sure because this branch runs if the length>1. grouped : queue[0].continent, countries : queue }; } //adds the whole array queue to the result destination.push(queue); //otherwise if there's one country only }else{ //adds the single country to the result destination.push(queue[0]); } } function groupCountries(array, useWrapper = false){ let result = []; let prevContinent; let queue = []; array.forEach((o, i)=>{ //if this isn't the first element and //the previous continent is different from the current one if(typeof prevContinent !== "undefined" && prevContinent != o.continent){ //flushes the queue of grouped countries to the result array flushQueue(queue, result, useWrapper); //resets the queue queue = []; } //adds the current country to the queue before it gets flushed in groups queue.push(o); //refresh prevContinent with the current value before turning to the next prevContinent = o.continent; }); //flush the remaining elements in the queue, before.. flushQueue(queue, result, useWrapper); //..returning the result return result; } let result; //first fashion result = groupCountries(array); console.log(result); //second fashion result = groupCountries(array, true); console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Esto debería hacerlo.

Hay una nueva matriz en blanco que almacena la respuesta.

El algoritmo simplemente itera a través de la matriz existente y guarda una matriz temporal de coincidencias. Cuando la siguiente entrada no coincide con la anterior, agrega esa matriz temporal a una nueva matriz.

 const array = [{ country: 'usa', continent: 'north america' }, { country: 'germany', continent: 'europe' }, { country: 'france', continent: 'europe' }, { country: 'india', continent: 'asia' }, { country: 'netherlands', continent: 'europe' }, ] const newArray = [] var tempArray = [] var previousContinent = "" array.forEach(item => { if (item.continent === previousContinent) { tempArray.push(item) } else { // Delete this first check if you don't mind every entry being an array if (tempArray.length === 1) { newArray.push(tempArray[0]) } else if (tempArray.length > 0) { newArray.push(tempArray) } previousContinent = item.continent tempArray = [item] } }) if (tempArray.length === 1) { newArray.push(tempArray[0]) } else if (tempArray.length > 0) { newArray.push(tempArray) } console.log(newArray)

about 4 years ago · Juan Pablo Isaza Report

0

Un método sería recorrer la matriz y almacenar el valor del último continent , si es el mismo que el elemento anterior, luego mover el elemento anterior a una matriz y agregar el elemento actual.

Array.reduce() podría usarse para esta tarea:

 const array = [ {country : 'usa', continent: 'north america'}, {country : 'germany', continent: 'europe'}, {country : 'france', continent: 'europe'}, {country : 'india', continent: 'asia'}, {country : 'netherlands', continent: 'europe'}, ]; const newArray = array.reduce((map, item) => { let prevItem = map[map.length-1]; //get prevous item // is previous continent matches current? if (prevItem && (prevItem.continent || (prevItem[0] && prevItem[0].continent)) === item.continent) { if (prevItem.continent) //if it's not an array, convert it into one { prevItem = [prevItem]; //convert prevous item into array map.splice(-1, 1, prevItem); //replace prevous item with new array'ed item } prevItem[prevItem.length] = item; //append current item to the array } else map[map.length] = item; return map; }, [] /* "map" array */); console.log(newArray);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!