Home > Mobile >  Find the longest Elements in a 2d array
Find the longest Elements in a 2d array

Time:04-13

I'm currently working with a 2d Array which is 6 rows long.

Now I need to filter the longest rows to work with them. But I dont know how to filter the shortest the element.

For example:

0: (3) ['karo11', 'karo6', 'kreuz13']
1: (2) ['pik6', 'pik13']
2: ['karo13']
3: (2) ['herz11', 'kreuz6']
4: ['herz6']
5: (2) ['kreuz11', 'pik11']

This is my array. Now I need to filter out row 2 and 4. But how should I do this?

Note. The Array is not static so the length of the rows are variable and change everytime I run the code

CodePudding user response:

One way might be to get the length of each array, find the minimum length and then filter the array where length is not equal to the minimum.

And if you need to filter out the max lengths, use Math.max() instead.

let arr = [
  ['karo11', 'karo6', 'kreuz13'],
  ['pik6', 'pik13'],
  ['karo13'],
  ['herz11', 'kreuz6'],
  ['herz6'],
  ['kreuz11', 'pik11']
]


let min = Math.min(...arr.map(i => i.length))

let result = arr.filter(i => i.length !== min)

console.log(result)

CodePudding user response:

You can use Math.max() and Math.min() to get the max and min length element from the array and then you can filter that out based on the requirement.

Demo :

const inputArr = [
  ['karo11', 'karo6', 'kreuz13'],
  ['pik6', 'pik13'],
  ['karo13'],
  ['herz11', 'kreuz6'],
  ['herz6'],
  ['kreuz11', 'pik11']
];

let shortest = inputArr.filter(i => i.length !== Math.max(...inputArr.map(i => i.length)))

let longest = inputArr.filter(i => i.length !== Math.min(...inputArr.map(i => i.length)))

console.log(shortest)
console.log(longest)

  • Related