I have for example this array [-3, 1, 2, 3, -1, 4, -2], and I’d like to return 4 because it doesn’t have its own opposite. I’ve been struggling for several hours to understand how to implement the algorithm.
This is what I’ve done so far:
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
}
}
>Solution :
You can try something like this:
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]
or using array functions:
const yourArray = [-3, 1, 2, 3, -1, 4, -2];
const itemsWithoutOpposite = yourArray.filter(el1 => !yourArray.includes(-el1));