Viết hàm findPositions() nhận hai mảng, trả về mảng chỉ số của tất cả phần tử mảng thứ hai xuất hiện trong mảng thứ nhất.
Ví dụ: mảng 1: ['john', 'doe', 'chris', 'snow', 'john', 'chris'], mảng 2: ['john', 'chris'] => [0, 2, 4, 5].
Dùng forEach trên mảng thứ nhất, nếu phần tử có trong mảng thứ hai thì push index.
Ví dụ
const values = ['michael', 'jordan', 'jackson', 'michael', 'usain', 'jackson', 'bolt', 'jackson'];
const queries = ['michael', 'jackson', 'bolt'];
const findPositions = (first, second) => {
const indicies = [];
first.forEach((element, index) => {
if (second.includes(element)) {
indicies.push(index);
}
});
return indicies;
};
console.log(findPositions(values, queries));Kết quả
Đầu ra trong console sẽ là:
[ 0, 2, 3, 5, 6, 7 ]