0

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;
  });
 }

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This works for me. The other solution brings me undefined in return.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.