Skip to main content

Interview question on arrays

Question 1 : Given an array of object group them with same keys.

Question 1 : Given an array of object group them with same keys.

const data = [
{ category: "fruit", name: "apple" },
{ category: "vegetable", name: "carrot" },
{ category: "fruit", name: "banana" },
{ category: "vegetable", name: "broccoli" },
{ category: "fruit", name: "pear" },
];


Output:
{
fruit: [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'fruit', name: 'pear' }
],
vegetable: [
{ category: 'vegetable', name: 'carrot' },
{ category: 'vegetable', name: 'broccoli' }
]
}

const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
const keyValue = currentValue[key];

// If the key doesn't exist in the result object, create it and set it as an empty array
if (!result[keyValue]) {
result[keyValue] = [];
}

// Push the current object to the corresponding key array
result[keyValue].push(currentValue);

return result;
}, {}); // Initialize the result object as an empty object
};

const groupedData = groupBy(data, "category");

Question 2 : Return the most repeating character from string

Question 2 : Return the most repeating character from string.
let s = "javascript";
output: a; // because a is most occurring
const mostRepeatingChar = (str) => {
const charCount = {};

// Count occurrences of each character
for (const char of str) {
if (charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}

// here charCount will become
// { j:1, a:2,...}

let maxCount = 0;
let mostRepeating = "";

// Find the character with the maximum count
for (const char in charCount) {
if (charCount[char] > maxCount) {
maxCount = charCount[char];
mostRepeating = char;
}
}

return mostRepeating;
};

// Example usage
const inputString = "javascript";
const result = mostRepeatingChar(inputString);
console.log(result); // Output: "a"

Question 3 : Implement a function that flattens a nested array.

Question 3 : Implement a function that flattens a nested array.
function flattenArray(arr) {
return arr.reduce((acc, curr) =>
acc.concat(Array.isArray(curr) ? flattenArray(curr) : curr),
[]);
}