Sobes.tech
Middle+

const customMap = (array, transform) => { // etwas wie array.map(transform); }; const stringResults = customMap([1, 2, 3], item => item.toString()); const lengths = customMap(["hallo", "welt"], item => item.length);

sobes.tech KI

Antwort von AI

Die Funktion customMap sollte ein Array und eine Transformationsfunktion akzeptieren und ein neues Array zurückgeben, in dem jedes Element das Ergebnis der Anwendung der Funktion auf das entsprechende Element des ursprünglichen Arrays ist. Dies ist analog zu Array.prototype.map.

Beispiel für die Implementierung:

const customMap = (array, transform) => {
  const result = [];
  for (let i = 0; i < array.length; i++) {
    result.push(transform(array[i], i, array));
  }
  return result;
};

const stringResults = customMap([1, 2, 3], item => item.toString());
console.log(stringResults); // ["1", "2", "3"]

const lengths = customMap(["hello", "world"], item => item.length);
console.log(lengths); // [5, 5]

Hier iterieren wir manuell über das Array, wenden die Funktion transform auf jedes Element an und sammeln die Ergebnisse in einem neuen Array.