-2

I have a multidimensional array

[
  ["apple" , 50],
  ["pie", 45]
  ["steak", 78]
]

I have one another array

["apple","pie"]

How can I filter first array into this result:

[
    ["apple" , 50],
    ["pie", 45]
]

function sorting(value){ 
  var sorted = new Array(); 
  for(var i =0; i <Object.keys(inputArray); i++)
  { 
    if (inputArray[i].keys === value)
    { 
      sorted.push(inputArray[i]); 
    } 
  } 
  return sorted; 
}

6
  • 3
    What have you tried so far? Commented Jun 5, 2018 at 22:09
  • this may be your solutionhttps://stackoverflow.com/questions/9206914/how-to-filter-multidimensional-javascript-array Commented Jun 5, 2018 at 22:14
  • 1
    Please note that Stackoverflow is not a free code writing service. The objective is for you to show what you have attemted to solve your issue and people help you with your code when it doesn't work as expected Commented Jun 5, 2018 at 22:14
  • function sorting(value){ var sorted = new Array(); for(var i =0; i <Object.keys(inputArray); i++){ if (inputArray[i].keys === value){ sorted.push(inputArray[i]); } } return sorted; } Commented Jun 5, 2018 at 22:15
  • @Rauf Did you find a different answer? Commented Jun 5, 2018 at 22:25

2 Answers 2

1

Try this:

var firstArray = [
  ["apple" , 50],
  ["pie", 45],
  ["steak", 78]
];
var secondArray = ["apple","pie"];

var thirdArray = [];

for (var i = 0; i < firstArray.length; i++) {
  if (secondArray.includes(firstArray[i][0])) {
    thirdArray.push(firstArray[i]);
  }
}
console.log(thirdArray);

This is of course used if you don't want to use the .filter method.

Sign up to request clarification or add additional context in comments.

Comments

0

you can use Array.filter() and Array.includes()

const arr1 = [
  ["apple", 50],
  ["pie", 45],
  ["steak", 78]
]

const arr2 = ["apple", "pie"]

const result = arr1.filter(e => arr2.includes(e[0]))

console.log(JSON.stringify(result))

2 Comments

why you stringify the end result?
Just for display purposes , not necessary

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.