No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

# Playground: implementa el método getAllKeys

14/29

Aportes 65

Preguntas 1

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Mi aporte

`````` getAllKeys(){
const array = this.data
let key = []

array.forEach((e) => {
e.forEach((k) => {
key.push(k[0]);
})
});
return key;
}
``````
``````  getAllKeys(){
return this.data
.flat()
.map(([name]) => name)
}
``````

Mi Solucion

``````getAllKeys(){
// Tu código aquí 👈
let items = this.data
.filter(item => item != undefined)
.flat()
.map(item => item[0])

return items;
}
``````
``````  getAllKeys(){
let keys = [];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i]) {
for (let j = 0; j < this.data[i].length; j++) {

if (this.data[i][j]) {
keys.push(this.data[i][j][0])
}

}

}
}
return keys;
}
``````

Se supone que el metodo no debe usar metodos:)

``````<code>
getAllKeys(){
// Tu código aquí 👈
const table = this.data;
const allKeys = []
for (let i = 0; i < table.length; i++) {
if (table[i]) {
for (let j = 0; j < table[i].length; j++) {
allKeys.push(table[i][j][0]);
}
}
}
return allKeys;
}
``````

Solución

``````  getAllKeys() {
const keys = [];
for (let bucket of this.data) {
if (bucket) {
for (let item of bucket) {
keys.push(item[0]);
}
}
}

return keys;
}
``````

Caso de prueba

``````test("Should return an array with all keys", () => {
const myHashTable = new MyHashTable(50);
const dataExpected = ["Diego", "Mariana", "Miranda", "Cat"];

myHashTable.set("Diego", 1990);
myHashTable.set("Mariana", 1998)
myHashTable.set("Miranda", 2000)
myHashTable.set("Cat", 2010)
const data = myHashTable.getAllKeys();

console.log(data);

expect(typeof myHashTable.data === "object").toBeTruthy();
expect(data).toHaveLength(4);
expect(data).toEqual(expect.arrayContaining(dataExpected));
});
``````
``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
// Tu código aquí 👈
let allValues = [];
for (const arr of this.data) {
if (arr) {
for (const element of arr) {
allValues.push(element[0]);
}
}
}
return allValues;
}
}
``````
```js import { HashTable } from "./hashTable.js" export class Solution extends HashTable { constructor(size){ super() this.data = new Array(size) } ```import { HashTable } from "./hashTable.js" export class Solution extends HashTable { constructor(size){ super() this.data = new Array(size) }
como no hacerlo: se me ocurrio aplanar el arreglo, y retornar los elementos pares del arreglo. estos deberian corresponder a las keys. pero no tube en cuenta que para que esta logica funcionara, todas las posiciones de la hash table deberian pocer un tupla almenos (key,value). pero esto nunca es asi, la hash se inicializa con un size definido, lo que hace que hallan elementos undefince cuando no halla tuplas, por lo que es imposible determinar que el arreglo aplanado tendra un numero par de elementos donde todos los pares seran keys (= ja ja ja a intentar otra vez ... y me sentia tan orgulloso de mi solucion getAllKeys(){  const flatten=this.data.flat(2)  const keys=new Array(flatten.length/2)  for(let i=0;i\<flatten.length;i+2){    keys\[i/2]=flatten\[i];  }  return keys}
```js getAllKeys() { const bucketList = this.data const keyList = [] for (const key in bucketList) { if (Object.hasOwnProperty.call(bucketList, key)) { const element = bucketList[key]; for (const keys in element) { const value = element[keys]; keyList.push(value[0]) } } } return keyList } ```    getAllKeys() {        const bucketList = this.data        const keyList = \[]        for (const key in bucketList) {            if (Object.hasOwnProperty.call(bucketList, key)) {                const element = bucketList\[key];                for (const keys in element) {                    const value = element\[keys];                    keyList.push(value\[0])                }            }        }        return keyList    }
```js const bucketList = this.data const keyList = [] for (const key in bucketList) { if (Object.hasOwnProperty.call(bucketList, key)) { const element = bucketList[key]; for (const keys in element) { const value = element[keys]; keyList.push(value[0]) } } } return keyList ```const bucketList = this.data        const keyList = \[]        for (const key in bucketList) {            if (Object.hasOwnProperty.call(bucketList, key)) {                const element = bucketList\[key];                for (const keys in element) {                    const value = element\[keys];                    keyList.push(value\[0])                }            }        }        return keyList
Mi solución \* \* \* \* \* \* \* ```js getAllKeys() { let keys = []; this.data.flat(1).forEach(bucket => { if (bucket[0]) { keys.push(bucket[0]); } }); return keys; } } ```
```js getAllKeys() { return this.data.flat(1).map(value => value[0]); } ```
MI solucion: ```js getAllKeys(){ // Tu código aquí 👈 const keysArray = []; for (const bucket of this.data) { // Verifico si el bucket existe y no está vacío if (bucket) { // Itero sobre los elementos en el bucket for (const [key] of bucket) { // Agrego la clave al array keysArray.push(key); } } } // Devuelvo el array con todas las claves return keysArray; } ```

reto :

Mi solución:

``````  getAllKeys() {
const keys = this.data
.filter(bucket => bucket !== null)
.map(bucket => bucket.map(entry => entry[0]))
.flat();

return keys;
}
``````

Solución 😄…

.
.
.
.

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
const keys = [];
for (let i = 0; i < this.data.length; i++) {
const currentBucket = this.data[i];
if (currentBucket) {
for (let j = 0; j < currentBucket.length; j++) {
keys.push(currentBucket[j][0]);
}
}
}
return keys;
}
}
``````

Aqui mi solución

``````getAllKeys(){
let keys = []
Object.values(this.data).forEach(bucket => {
keys = keys.concat(bucket.map(entry => entry[0]));
})
return keys;
}
``````

Esta fue mi solución, similar a algunas soluciones
<
<
<
<
<
<
<
<
<<
<
<
<
<
<
<

``````    getAllKeys(){
const keys = []

for (const bucket of this.data) {
if (bucket) {
for (const item of bucket) {
keys.push(item[0])
}
}
}
return keys
}
``````

Esta es la solución del reto usando Array Methods 💚

Acá pueden probar el código

``````getAllKeys(){
return this.data.reduce((accumulator, currentDataArray) => {
const keys = currentDataArray.map(([key]) => key)
return accumulator.concat(keys)
}, [])
}
``````

Mi aporte!

`````` getAllKeys() {
let keys = [];
for (let i = 0; i <this.data.length; i += 1) {
const currentBucket = this.data[i];
if (currentBucket) {
for (let j = 0; j < currentBucket.length; j++) {
if (currentBucket[j][0]) {
const firstKey = currentBucket[j][0];
keys.push(firstKey);
}
}
}
}
return keys;
}
``````

MI solución al reto:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys() {
const data = this.data;
let keys = [];
for (let i = 0; i < data.length; i++) {
const key = this.data[i];

if (key != undefined) {
const currentKey = key
if (currentKey.length > 1) {
for (let j = 0; j < currentKey.length; j++) {
const keyResult = currentKey[j][0];
keys.push(keyResult)
}
}

if (currentKey.length === 1) {
const flatKey = key.flat();
for (let j = 0; j < flatKey.length - 1; j++) {
const keyResult = flatKey[0];
keys.push(keyResult)
}
}
}
}
return keys;
};
}
``````

``````getAllKeys() {
let info = []

this.data.forEach( data => {
if( data ) {
let colecttion = data.map( element => element[0])
info.push(colecttion)
}
});

return info.flat()
}
``````

Mi aporte:
*
*
*
*
*
*
*
*
*
getAllKeys(){
const buckets = this.data;
let keysHash = [];

``````if (buckets.length > 0) {

for (let i = 0; i < buckets.length; i++) {

if (buckets[i]) {

if (buckets[i].length > 1) {

for (let j = 0; j < buckets[i].length; j++) {
let bucket = buckets[i][j];
keysHash.push(bucket[0]);

}

} else {
let bucket = buckets[i][0];
keysHash.push(bucket[0]);

}

}
}
return keysHash;
}
return undefined;
``````

}

Mi solucion con ES6

``````/*
*
*
*
*
*
*
*
*/
getAllKeys(){
return this.data
.map((item) => item && item.map((subitem) => subitem[0]))
.flat();
}
``````

### Mi solución

``````
import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys() {

const keys = [];

for (let i = 0; i < this.data.length; i++) {

const element = this.data[i];

if (element && element.length > 0) {

for (let i = 0; i < element.length; i++) {

keys.push(element[i][0])

}

}

}

return keys;

}

}

``````

Mi solución:
.
.
.
.
.
.
.
.
.
.

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
const newArr = [];

for (let i = 0; i < this.data.length; i++) {
if (this.data[i]) {
this.data[i].forEach(item => {
newArr.push(item[0]);
})
}
}

return newArr;
}
}

``````

## Mi solución usando ciclos for

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys() {
return this.data.flat().map((el) => el[0])
}
}

``````

usando reduce

``````getAllKeys() {
return this.data.reduce((keys, bucket) => {
if (bucket) {
const bucketKeys = bucket.map((entry) => entry[0]);
return [...keys, ...bucketKeys];
}
return keys;
}, []);
}
``````

Mi solución:

getAllKeys() {
const keys = [];
for (let i = 0; i < this.data.length; i++) {
const currentBucket = this.data[i];
if (currentBucket) {
for (let k = 0; k < currentBucket.length; k++) {
keys.push(currentBucket[k][0]);
}
}
}
return keys;
}

🪂
🪂
🪂
🪂
🪂
🪂
🪂
🪂
🪂
🪂
🪂
🪂

``````  getAllKeys() {
let allNivelData = this.data.flat(2);
let allKeys = []
for (let i = 0; i < allNivelData.length; i++) {
if (i % 2 == 0) {
allKeys.push(allNivelData[i])
}
}
return allKeys;
}
``````

Yo utilicé un método flatMap
*
*
*
*
*
*
*
*
*
*
getAllKeys() {
let keys = [];
this.data
.flat()
.flatMap((element) => element === undefined ? [] : keys.push(element[0]) );
return keys;
}

Mi solucion

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys() {
return this.data.flat().map(([key]) => key)
}

}

``````

una solución bastante sencilla
.
.
.
.
.
.
.
.
.
.
.

``````getAllKeys() {
const result = [];
const flattenedList = this.data.flat();
// we flattend the lit usgin the flat method of the arrays to get something like this:
// [ [ 'Diego', 1990 ], [ 'Mariana', 2000 ], [ 'Javier', 2000 ] ]

// then we iterate over the flattened list to get all the keys of each tuple
for (let i = 0; i < flattenedList.length; i += 1) {
result.push(flattenedList[i][0])
}

return result
}
``````

Mi solución
.
.
.
.
.
.
.
.
.
.
.

``````getAllKeys(){
const keys = new Set()
this.data
.flat()
return [...keys]
}
``````
``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
// Tu código aquí 👈
let keys = []

this.data.map((item) => {
item.map((i) => {
keys.push(i[0])
})
})

return keys.length > 0 ? keys : keys
}
}

``````

Mi solucion
.
.
.
.
.
.
.
.
.

``````getAllKeys(){
const occupiedSpaces = this.data.filter(i => i != null).flat();
const allKeys = occupiedSpaces.map(i => i[0]);
return allKeys
}
``````

Creo que se puede hacer un con flapMap aunque no domino bien ese método aquí esta mi respuesta.

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
return this.data.flat().map(item => item[0])
}
}
``````

Mi aporte:

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
// Tu código aquí 👈
const keys = [];
this.data.forEach(bucket => {

bucket.forEach((item) => {
return keys.push(item[0]);
})
})
return keys;
}
}

``````

.
.
.
.

``````getAllKeys(){
const keys = [];
this.data.forEach(bucket => {
bucket.forEach((item, index) => {
return keys.push(bucket[index][0]);
})
})
return keys;
};
``````

Sin Saber en la clase coloqué la respuesta a ambos playgrounds

``````    getAllKeys() {
const keysArray = [];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i]) {
for (let j = 0; j < this.data[i].length; j++) {
keysArray.push(this.data[i][j][0]);
}
}
}
return keysArray;
}
``````

Solución

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys() {
// Tu código aquí 👈
return this.data.flat().map(key => key[0]);
}
}
``````

Creo que esta fue la parte más fácil de todas jaja, mi aporte… 😃

getAllKeys() {
// Tu código aquí 👈
let arr = [];
for (let i of this.data) {
if (typeof i === “object”) {
for (let j = 0; j < i.length; j++) {
arr.push(i[j][0]);
}
}
}
return arr;
}

``````  getAllKeys(){
return this.data.flat().map(value => value[0]);
}
``````

Así fue mi solución usado forEach 😃

``````# Obtiene todas las llaves de array data
getAllKeys(){
let keys = []
this.data.forEach(element => {
if(element.length > 1){
element.forEach(element => {
keys.push(element[0])
})
}else{
keys.push(element[0][0]);
}
});
return keys;
}
``````

Les comparto mí solución

``````  getAllKeys(){
const allKeys = this.data.map(bucket => {
if (bucket) {
const allKeyBucket = bucket.flatMap(item => item[0]);
return allKeyBucket;
}
});
return allKeys.flat();
}
``````

Dejo aquí la forma en la que lo solucioné por si le es de utilidad a alguien

``````    getAllKeys(){
const table = this.data;
let arr = [] //24
for(let i = 0; i< table.length; i++){  // bucle para recorrer todos los valores de la tabla
if(table[i]){   //si hay valor en este index
arr.push(table[i][0][0]) // agrega el valor a la variable arr
if(table[i].length>1){ // comprobar si hay mas valores en la misma entrada
for(let j = 1; j<table.length;j++){
arr.push(table[i][1][0])
}
}
}
}
console.log(arr)
return arr;
}
}
``````

mi respuesta
*
*
*
*
*
*
*

``````let result = [];
for(let i=0; i < this.data.length; i++){
if(this.data[i]){
this.data[i].forEach(element => {result.push(element[0])})

console.log(result)
}
}
return result
``````

mi solucion:
.
.
.
.
.
.
.
.

.
.
.

``````getAllKeys() {
let keys = [];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i]) { // if (this.data[i].length > 0) {
for (let j = 0; j < this.data[i].length; j++) {
let current = this.data[i];
console.log('se agrega al array de keys a ' + current[j][0]);
keys.push(current[j][0]);
}
} else {
// la fila esta vacia
}
}
return keys;
}
``````

the best solution ever

``````getAllKeys(){
let allkeys = [];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i]) {
if (this.data[i].length > 1) {
for (let j = 0; j < this.data[i].length; j++) {
allkeys.push(this.data[i][j][0]);
}
} else {
allkeys.push(this.data[i][0][0]);
}
}
}
return allkeys;
}
``````

let existKeys = [];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i]) {
let bucketData = this.data[i];
for (let i = 0; i < bucketData.length; i++) {
existKeys.push(bucketData[i][0]);
}
}
}
return existKeys;

Por aprender flat y map
Flat, por el momento lo hice con puro map

``````<code>
getAllKeys(){
const buckets = this.data.filter(bucket => bucket !== null)
const keys = buckets.map(bucket => {
return bucket.map(arr => arr[0])
})
return keys.join().split(",")
}
``````
``````getAllKeys() {
const newArray = [];

this.data.forEach(array => {
array.forEach(bucket => {
newArray.push(bucket[0]);
})
})

return newArray;
}
``````

Acá mi solución

`````` getAllKeys() {
const data = this.data;
const keys = data.flat().map(key => key[0]);
return keys;
}
``````
``````getAllKeys(){
const allKeys = [];
const allBuckets = Object.values(this.data);
for (let index = 0; index < allBuckets.length; index++) {
for (let indexInterior = 0; indexInterior < allBuckets[index].length; indexInterior++) {
allKeys.push(allBuckets[index][indexInterior][0]);
}
}
return allKeys;
}
``````

Me costo, pero llegue a esta solución

``````export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
// Tu código aquí 👈
const listWithoutEmpty = this.data.filter((bucket) => (
bucket && bucket.length > 0
));

const keys = listWithoutEmpty
.flat()
.map(([key]) => key);

return keys;
}
}
``````

🥄

``````  getAllKeys() {
if (this.data.length) {
const keys = [];
this.data.forEach(element => {
element.forEach(subElement => keys.push(subElement[0]))
})
return keys;
} return undefined;
}
``````

Hola compañeros, anexo mi resultado para los retos

delete

`````` delete(key) {
if (currentBucket) {
for (let i = 0; i < currentBucket.length; i++) {
if (currentBucket[i][0] === key) {
const item = currentBucket[i];
return item;
}
}
}
return undefined;
}
``````

getAll

``````  getAll() {
const newArray = [];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i]) {
if (this.data[i].length === 1) {
newArray.push(this.data[i][0][0]);
} else {
for (let j = 0; j < this.data[i].length; j++) {
if (this.data[i][j]) {
newArray.push(this.data[i][j][0]);
}
}
}
}

}
return newArray;
}
``````

Importante caer en cuenta acá que nuestra hash table está guardada en un ARREGLO (this.data = new Array(size)), así que para resolver este problema, hay que tratar nuestra hash table como array.

``````  getAllKeys(){
const keys = [];
for (let bucket of this.data) {
if (bucket) {
for (let keyValue of bucket) {
keys.push(keyValue[0]);
}
}
}
return keys;
}

``````

Mi solución comentada para mayor entendimiento del código.

.

.

.

.

.

.

.

.

.

.

``````  getAllKeys() {
//* filtro solo los buckets con datos
const filtered = this.data.filter(data => data !== undefined)
//* Creo un array vacio, donde pusheare mis keys
let result = []
//* Recorro el array con los buckets filtrados
filtered.forEach(ele => {
//* Si el bucket tiene colision se recorre nuevamente y pushea a mi
//* array de resultado. Si no hay colision se pushea normalmente.
if (ele.length > 1) {
ele.forEach(ele => {
result.push(ele[0])
})
} else {
result.push(ele[0][0])
}
})

return result
}
``````

Yo lo hice con métodos de un array.
.

.

.

.

.

.

.

.

.

.

.

.

``````import { HashTable } from "./hashTable.js"

export class Solution extends HashTable {
constructor(size){
super()
this.data = new Array(size)
}

getAllKeys(){
const data = this.data.filter((item) => item.length);
const items = data.flat();
const response = items.map(([key]) => key);

return response;
}
}

``````
```js getAllKeys() { const keys = []; for (let currentBucket of this.data) { if (currentBucket) { for (let keysCatch of currentBucket) { keys.push(keysCatch[0]); } } } return keys; } } ```
undefined