Cesar Jr Rodriguez
Cesar Jr Rodriguez

Reputation: 1821

Can't return a value from map iteration in Javascript

I'm having problems when trying to return a value encountered from a .map using Javascript. There's my code:

function LineaDeSuccion() {
  const carga = vm.cargaTotal / vm.numeroEvaporadores;
  vm.succion.map(i => {
    if (i.temperatura == vm.tempSel) {
      const cargas = Object.keys(i).map(function(key) {
        return i[key];
      });
  // I need to return this value in my function
  return getKeyByValue(i, closest(cargas, carga));
  }
  // Obviously I can't do it because the value it's encapsulated into the map callback.
  // How can I solve it?
  return value;
  });
 }

Upvotes: 0

Views: 144

Answers (2)

qntm
qntm

Reputation: 4407

One approach is to use Array.prototype.find to find the value you want in the array, then perform the transformation you need once you have it.

function LineaDeSuccion() {
    const carga = vm.cargaTotal / vm.numeroEvaporadores;
    const i = vm.succion.find(i => i.temperatura == vm.tempSel);

    if (i === undefined) {
        throw Error("can't find what I want in the array");
    }

    const cargas = Object.keys(i).map(function (key) {
        return i[key];
    });

    return getKeyByValue(i, closest(cargas, carga));
}

Note that this approach will not iterate over the entire array but break out of the find loop immediately once a match is found. If there are several elements i in the array which satisfy the condition i.temperatura == vm.tempSel, this will return the first match, not the last.

Upvotes: 1

Christian Santos
Christian Santos

Reputation: 5456

If you want to return a value outside of your map, you'll have to set a variable that lives outside of your map, and then set that value within your map:

function LineaDeSuccion() {

    const carga = vm.cargaTotal / vm.numeroEvaporadores;

    let value = "defaultValue"; // default value

    vm.succion.map(i => {

        if (i.temperatura == vm.tempSel) {

            const cargas = Object.keys(i).map(function(key) {
                return i[key];
            });

            value = getKeyByValue(i, closest(cargas, carga)); // new set value
        }
    });

    return value;
}

Upvotes: 0

Related Questions