比较两个对象中所有字段都相同,并以对象形式返回
function getSameFieldsAndValues(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
const sameFieldsAndValues = {};
for (let key of keys1) {
if (obj1[key] === obj2[key]) {
sameFieldsAndValues[key] = obj1[key];
}
}
return sameFieldsAndValues;
}
注:
该函数使用一个空对象来存储相同键值的键值对。如果两个对象有相同的键值,则将该键值和对应的值存储到新对象中。返回的对象将包含相同的键值和对应的值。
以下是使用该函数来获取两个对象相同的字段和对应值的示例代码:
const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { a: 1, b: 2, c: 4 };
const obj3 = { a: 1, b: 2, c: 3 };
console.log(getSameFieldsAndValues(obj1, obj2)); // { a: 1, b: 2 }
console.log(getSameFieldsAndValues(obj1, obj3)); // { a: 1, b: 2, c: 3 }
将一个数组分割多个
方法一
/**
*
* @param {*} array 传入的数组
* @param {*} subGroupLength 分割数量
*/
arraySplit(array, subGroupLength) {
let index = 0;
let newArray = [];
while (index < array.length) {
newArray.push(array.slice(index, (index += subGroupLength)));
}
return newArray;
},
// 使用
let arr = this.arraySplit(list, 2);
方法二
function arraySplit(array, subGroupLength) {
return Array.from({ length: Math.ceil(array.length / subGroupLength) }, (_, index) =>
array.slice(index * subGroupLength, index * subGroupLength + subGroupLength)
);
}
首先使用Math.ceil()方法计算分割后的子组数量。然后,我们使用Array.from()方法创建一个长度为子组数量的新数组。
在Array.from()方法的第二个参数中,我们使用箭头函数来处理每个新数组的创建。箭头函数中的两个参数分别是当前元素的值和索引,由于我们只需要使用索引,所以我们用“_”来忽略值。在函数的主体中,我们使用Array.splice()方法从原始数组中选择子组,并将其添加到新数组中。
下面是使用上述代码实现的示例:
const originalArray = [1, 2, 3, 4, 5, 6, 7, 8];
const subGroupLength = 3;
const result = arraySplit(originalArray, subGroupLength);
console.log(result); // [[1, 2, 3], [4, 5, 6], [7, 8]]