Add 2D array item to new array based on string variable

Viewed 30

Received is an input of arrays:

var fruits = [["fuji", "apple"], ["gala", "apple"], ["navel", "orange"], ["valencia", "orange"]]

I have blank arrays created:

var apple = [] 
var orange = []

I'd like to sort the fruits into their arrays by getting the string out of the second array item and push to the array. Is there a way to take that string value in fruits[i][1] and relate it to the array of the same name (apple/orange)?

for (var i = 0; i < fruits.length; i++) {
  fruits[i][1].push(fruits[i])  // not a thing
  }

Desired output:

apple == [["fuji", "apple"], ["gala", "apple"]]
orange == [["navel", "orange"], ["valencia", "orange"]]
2 Answers

You can use Array.prototype.filter() :

var apple = fruits.filter((ele) => ele[1] === "apple");
var orange = fruits.filter((ele) => ele[1] === "orange");

Write the sort compare method using the second element in item.

var fruits = [
  ["fuji", "apple"],
  ["gala", "apple"],
  ["navel", "orange"],
  ["valencia", "orange"],
];

const sorted = (arr, key) => {
  return [...arr].sort(([, a], [, b]) => {
    return a === key ? -1 : 1;
  });
};

console.log(sorted(fruits, "apple"));
console.log(sorted(fruits, "orange"));

Related