I have an dataset like this:
const array = [
{
id: '5c1b4ffc18e2d84b7d6feaf3',
model: 'sedan',
carname: 'Audi a8',
type: 'car'
},
{
id: '5c1b4ffc18e2d84b7d6feaf3',
model: 'cruiser',
carname: 'Harley',
type: 'bike'
},
{
id: '5c1b4ffc18e2d84b7d6feaf3',
model: 'sports',
carname: 'Ninja',
type: 'bike'
},
{
id: '5c1b4ffc18e2d84b7d6feaf3',
model: 'sedan',
carname: 'BMW',
type: 'car'
},
{
id: '5c1b4ffc18e2d84b7d6feaf3',
model: 'sports',
carname: 'Hayabusa',
type: 'bike'
},
{
id: '5c1b4ffc18e2d84b7d6feaf3',
model: 'hatchback',
carname: 'Micra',
type: 'car'
},
]
NOTE: This is raw data with shorter length. Actual data will be like 10M+ enteries. What I want is like I want to preserve the only 1 or 2 data from the array and rest bike data will be filter out from an Array.
Now for this, the method I choose is like this:
let newArray = []
let cou = 0
array.map((x) => {
if (x.type === 'bike') {
cou++;
// Want to preserve only 1 data of bike
if (cou < 2) {
newArray.push(x)
}
} else {
newArray.push(x)
}
})
Is there any best approach for handling this type of problem. Actually I want to reduce the array iteration as it consume the memory and time of the code. Any solution or suggestion is highly appreciated. Thanks in advance for the interaction with the problem set.