A continuación se muestra un código que estoy usando
const account1 = { owner: 'Jonas Schmedtmann', movements: [200, 450, -400, 3000, -650, -130, 70, 1300], interestRate: 1.2, // % pin: 1111, }; const account2 = { owner: 'Jessica Davis', movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30], interestRate: 1.5, pin: 2222, }; const account3 = { owner: 'Steven Thomas Williams', movements: [200, -200, 340, -300, -20, 50, 400, -460], interestRate: 0.7, pin: 3333, }; const account4 = { owner: 'Sarah Smith', movements: [430, 1000, 700, 50, 90], interestRate: 1, pin: 4444, }; const accounts = [account1, account2, account3, account4]; const index = accounts.findIndex(function (acc) { acc.pin === 2222; }); console.log(index);
El resultado esperado es 1, pero ¿por qué obtengo -1? Obtengo -1 para cualquier condición que ponga en el método findIndex.
Solo necesita hacer el retorno dentro de la función findIndex (para devolver el índice donde la condición es verdadera). Cuando findIndex no coincide con algún resultado, devuelve -1.
const account1 = { owner: 'Jonas Schmedtmann', movements: [200, 450, -400, 3000, -650, -130, 70, 1300], interestRate: 1.2, // % pin: 1111, }; const account2 = { owner: 'Jessica Davis', movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30], interestRate: 1.5, pin: 2222, }; const account3 = { owner: 'Steven Thomas Williams', movements: [200, -200, 340, -300, -20, 50, 400, -460], interestRate: 0.7, pin: 3333, }; const account4 = { owner: 'Sarah Smith', movements: [430, 1000, 700, 50, 90], interestRate: 1, pin: 4444, }; const accounts = [account1, account2, account3, account4]; const index = accounts.findIndex(function (acc) { return acc.pin === 2222; }); console.log(index);
Y prefiero el código como este:
const accounts = [ { owner: 'Jonas Schmedtmann', movements: [200, 450, -400, 3000, -650, -130, 70, 1300], interestRate: 1.2, // % pin: 1111, }, { owner: 'Jessica Davis', movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30], interestRate: 1.5, pin: 2222, }, { owner: 'Steven Thomas Williams', movements: [200, -200, 340, -300, -20, 50, 400, -460], interestRate: 0.7, pin: 3333, }, { owner: 'Sarah Smith', movements: [430, 1000, 700, 50, 90], interestRate: 1, pin: 4444, } ]; const index = accounts.findIndex(function (acc) { return acc.pin === 2222; }); console.log(index);