繰り返されるものを置き換える2つのJavaScript配列の既存のメンバーと繰り返されるメンバーを持つオブジェクトの2つの配列を追加する
次のオブジェクトの配列があります。これらを1つにマージして、プロパティ名に冗長な値を持つオブジェクトを削除する必要があります-
const first = [{
name: 'Rahul',
age: 23
}, {
name: 'Ramesh',
age: 27
}, {
name: 'Vikram',
age: 35
}, {
name: 'Harsh',
age: 34
}, {
name: 'Vijay',
age: 21
}];
const second = [{
name: 'Vijay',
age: 21
}, {
name: 'Vikky',
age: 20
}, {
name: 'Joy',
age: 26
}, {
name: 'Vijay',
age: 21
}, {
name: 'Harsh',
age: 34
}, ] 関数combineArrayを定義し、2つの配列を取り込んで引数として結合し、新しい配列を返します-
const combineArray = (first, second) => {
const combinedArray = [];
const map = {};
first.forEach(firstEl => {
if(!map[firstEl.name]){
map[firstEl.name] = firstEl;
combinedArray.push(firstEl);
}
});
second.forEach(secondEl => {
if(!map[secondEl.name]){
map[secondEl.name] = secondEl;
combinedArray.push(secondEl);
}
})
return combinedArray;
}
console.log(combineArray(first, second)); この関数は、2番目の配列から重複するエントリを確実に削除するだけでなく、最初の配列に重複するエントリが存在する場合は、それも削除します。
これが完全なコードです-
例
const first = [{
name: 'Rahul',
age: 23
}, {
name: 'Ramesh',
age: 27
}, {
name: 'Vikram',
age: 35
}, {
name: 'Harsh',
age: 34
}, {
name: 'Vijay',
age: 21
}];
const second = [{
name: 'Vijay',
age: 21
}, {
name: 'Vikky',
age: 20
}, {
name: 'Joy',
age: 26
}, {
name: 'Vijay',
age: 21
}, {
name: 'Harsh',
age: 34
}, ]
const combineArray = (first, second) => {
const combinedArray = [];
const map = {};
first.forEach(firstEl => {
if(!map[firstEl.name]){
map[firstEl.name] = firstEl;
combinedArray.push(firstEl);
}
});
second.forEach(secondEl => {
if(!map[secondEl.name]){
map[secondEl.name] = secondEl;
combinedArray.push(secondEl);
}
})
return combinedArray;
}
console.log(combineArray(first, second)); 出力
コンソール出力は-
になります[
{ name: 'Rahul', age: 23 },{ name: 'Ramesh', age: 27 },{ name: 'Vikram', age: 35 },
{ name: 'Harsh', age: 34 },{ name: 'Vijay', age: 21 },{ name: 'Vikky', age: 20 },
{ name: 'Joy', age: 26 }
] -
JavaScriptで画像の明るさとコントラストを設定するにはどうすればよいですか?
明るさを設定するには、明るさを使用します プロパティとコントラストには、コントラストプロパティを使用します。 例 次のコードを実行して、JavaScriptで画像フィルターを使用することができます- <!DOCTYPE html> <html> <body> <p>Click below to change the brightness and contrast of the image.</p> <button o
-
JavaScriptでサブオブジェクトと配列を持つオブジェクトをインポートする方法は?
以下は、JavaScriptでサブオブジェクトと配列を含むオブジェクトをインポートするためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> &