Tengo, por ejemplo, esta matriz [-3, 1, 2, 3, -1, 4, -2] y me gustaría devolver 4 porque no tiene su propio opuesto. He estado luchando durante varias horas para entender cómo implementar el algoritmo. Esto es lo que he hecho hasta ahora:
let numbers = [-3, 1, 2, 3, -1, 4, -2]; let sortedNumebrs = []; //It returns the numbers array sorted function sortedArray() { sortedNumebrs = numbers.sort((a, b) => a - b); return sortedNumebrs; } // It return an array with all positive numbers function positive() { let positive = sortedArray().filter((e) => Math.sign(e) === 1); return positive; } // It return an array with all negative numbers function negative() { let negative = sortedNumebrs.filter((e) => Math.sign(e) === -1); negative = negative.sort((a, b) => a + b); return negative; } // It returns the array longer function minLength() { let minNum = Math.min(positive().length, negative().length); if (minNum === positive().length) { return positive() } else { eturn negative(); } } // It returns the array shorter function maxLength() { let maxNum = Math.max(positive().length, negative().length); if (maxNum === positive().length) { return positive() } else { return negative(); } } // Function that should return string if each numbers has its // own opposite otherwise 4 function opposite() { let result = (minLength() === maxLength()) ? true : false; if (result) { return 'Each element has own opposite'; } else { // some code } }Puedes intentar algo como esto:
const yourArray =[-3, 1, 2, 3, -1, 4, -2]; const result = []; for (let el1 of yourArray) { let hasOpposite = false; for (let el2 of yourArray) { if (el1 === -el2) { hasOpposite = true; break; } } if (!hasOpposite) { result.push(el1); } } console.log(result); // [4]o usando funciones de matriz:
const yourArray = [-3, 1, 2, 3, -1, 4, -2]; const itemsWithoutOpposite = yourArray.filter(el1 => !yourArray.includes(-el1));Aquí hay otro enfoque. Este supone que los duplicados también necesitan coincidir, por lo que si tengo [1, -1, 1], ese 1 final debería tener un -1 adicional para coincidir, en lugar de usar el -1 que coincidió con el 1 inicial. También lo hará no empareja un elemento consigo mismo, por lo que si tiene un 0 necesitará otro cero para emparejar.
const yourArr = [-3, 1, 2, 3, -1, 4, -2]; const result = [...yourArr]; for (let i = 0; i < result.length; i++) { let el = result[i]; let inverse = result.indexOf(-el, i + 1); if (inverse !== -1) { result.splice(inverse, 1); result.splice(i, 1); i--; } } console.log(result);