Encuentro que las matrices JS son enloquecedoras, intento ubicar la 'fila' de un elemento pasado en una matriz 2D (JS). No estaría teniendo estos problemas en otros idiomas. He intentado dos enfoques completamente diferentes, ninguno de los cuales proporciona un resultado adecuado. Así es como estoy creando la matriz 2D, y parece ser funcional:
var _rooms = []; var _User = function(roomNo, name) { this.roomNumber = roomNo; this.LeaderName = name; }; _rooms.push( new _User(1, "katy") ); _rooms.push( new _User(23, "Sara") );Aquí está el primer intento de ubicar una fila # de un 'nombre' pasado:
function findPosition(str) { var _locater, _sought, _seeks; for (_locater = 0; _locater < _rooms.length; _locater++) { _seeks = _rooms[_locater]; _sought = _seeks.indexOf(str); if (_sought >= 0) { return "row: " + _locater + ", col: " + _sought; } } } console.log(findPosition('Sara')); //SOURCE: "https://stackoverflow.com/questions/46540878/finding-row-and-column-of-a-multidimensional-array-in-javascript"Esto arroja un typeError, algo así como "_seeks.indexOf(str) no es una función". Aquí hay otro intento:
function indexOf2dArray(itemtofind) { var _sought _sought = [].concat.apply([], ([].concat.apply([], _rooms))).indexOf(itemtofind); // return "false" if the item is not found if (_sought === -1) { return false; } // Use any row to get the rows' array length // Note, this assumes the rows are arrays of the same length numColumns = _rooms[0].length; // row = the index in the 1d array divided by the row length (number of columns) row = parseInt(_sought / numColumns); // col = index modulus the number of columns col = _sought % numColumns; return [row, col]; } console.log("Sara is located: " + indexOf2dArray("Sara")) console.log("katy is located: " + indexOf2dArray("katy")) //SOURCE: https://lage.us/Javascript-Item-in-2d-Array-Using-indexOf.htmlEl resultado de este enfoque es "falso" para cada una de las declaraciones de console.log. ¿Alguien puede sugerir un método confiable para ubicar la 'fila' que aparece en un elemento buscado en una matriz 2D de JavaScript ...? Cualquier sugerencia muy apreciada.
Si está familiarizado con otros idiomas que imagino que tienen clases definibles, ¿por qué no usar clases de JavaScript ?
Cree una clase de User y una clase de Users que tenga una matriz a la que pueda agregar cada objeto de usuario.
Users pueden tener un método que localice el índice del usuario cuyo nombre le pasa.
class Users { // Add the array of users constructor(users) { this.users = users; } // Use `findIndex` to return the index // of the array given the `name` argument findPosition(name) { const index = this.users.findIndex(obj => { return obj.name === name; }); return `${name} is on row ${index}`; } }; class User { // Destructure the id and name from the user object constructor({ id, name }) { this.id = id; this.name = name; } } // `Users` accepts an array of user objects const users = new Users([ new User({ id: 1, name: 'Katy' }), new User({ id: 9, name: 'Boris' }), new User({ id: 23, name: 'Sara' }) ]); // And now you can call the users method // to find the index of the user in the array console.log(users.findPosition('Boris')); console.log(users.findPosition('Sara')); console.log(users.findPosition('Katy'));Documentación adicional
Manteniendo la mayor parte de su código original, puede hacer algo como esto:
var _rooms = []; var _User = function (roomNo, name) { this.roomNumber = roomNo; this.LeaderName = name; }; _rooms.push(new _User(1, 'katy')); _rooms.push(new _User(23, 'Sara')); function findPosition(str) { var _locater, _sought, _seeks; for (_locater = 0; _locater < _rooms.length; _locater++) { _seeks = _rooms[_locater]; // _seeks is a _User _sought = _seeks.LeaderName.indexOf(str); if (_sought >= 0) { return 'row: ' + _locater + ', col: ' + _seeks.roomNumber; } } } console.log(findPosition('Sara')); // prints "row: 1, col: 23" console.log(findPosition('kat')); // prints "row: 0, col: 1" console.log(findPosition('Joe')); // prints "undefined"Otra forma podría ser usar JavaScript más "moderno":
function findPosition2(str) { const roomIndex = _rooms.findIndex((user) => user.LeaderName.includes(str)); if (roomIndex >= 0) { return `row: ${roomIndex}, col: ${_rooms[roomIndex].roomNumber}`; } else { return 'not found'; } } console.log(findPosition2('Sara')); // prints "row: 1, col: 23" console.log(findPosition2('kat')); // prints "row: 0, col: 1" console.log(findPosition2('Joe')); // prints "not found"