2

I'm trying to get the other item out of an array. I have an array called fruit and a variable called apples. I want to go through the array and find any other fruit apart from the one I already have.

Thanks in advance for any help

var fruit =  [
        "apples",
        "pears"
    ];

var alreadyHave = "apples";


for( var i = 0; i < fruit.length; i++){
    if (! fruit[i] === alreadyHave) {
        fruit.splice(i, 1); 
    }
}

console.log(fruit);


I would like to set the remaining fruit as another variable.

Fazberry
  • 98
  • 8
  • Possible duplicate of [How to remove item from array by value?](https://stackoverflow.com/questions/3954438/how-to-remove-item-from-array-by-value) – Patryk Falba Aug 22 '19 at 11:05

5 Answers5

1

You can use the filter method for this:

const leftFruits = fruit.filter(f => f !== alreadyHave);
Maksym Bezruchko
  • 1,078
  • 3
  • 19
0

Simply use filter() function

var fruit =  [
        "apples",
        "pears"
    ];

var alreadyHave = "apples";
console.log(fruit.filter(x => x !== alreadyHave))
Dominik Matis
  • 1,719
  • 5
  • 14
0

You can use Array#filter to achieve this:

var alreadyHave = "apples";

var fruit = [
  "apples",
  "pears",
  "banana",
  "orange"
];

/* Create a new variable/array with all fruit items except for apples */
var remainingFruit = fruit.filter(item => alreadyHave !== item);

console.log(remainingFruit);
Dacre Denny
  • 26,362
  • 5
  • 28
  • 48
0

Use javascript filter() method for it

var fruit =  [
    "apples",
    "pears"
];

var alreadyHave = "apples";

var filteredFruit = fruit.filter(item => item !== alreadyHave);
Varun Arya
  • 147
  • 9
0

let fruit = [ "apples", "pears" ];

let alreadyHave = "apples";

let fruitsExceptAlreadyHave = fruit.filter(element => element !== alreadyHave);

Adnan Tariq
  • 157
  • 4