英文:
Find unique array of objects dynamically considering undefined values
问题
以下是您要翻译的代码部分:
const myArray = [
{
one: 'A',
two: 'AB'
},
{
one: undefined,
two: 'AB'
},
{
one: 'A',
two: 'BC'
},
{
one: undefined,
two: 'CC'
}
]
const outputMyArray = [
{
one: 'A',
two: 'AB'
},
{
one: 'A',
two: 'BC'
},
{
one: undefined,
two: 'CC'
}
]
这段代码描述了一个数组和所需的格式转换,其中如果one
为undefined
,但在另一个对象中存在two
,则忽略该对象。
英文:
I have a an array of objects in this format:
const myArray = [
{
one: 'A',
two: 'AB'
},
{
one: undefined,
two: 'AB'
},
{
one: 'A',
two: 'BC'
},
{
one: undefined,
two: 'CC'
},
]
I want the output in this particular format where if one is undefined but two is present in another object then ignore that object.
e.g., output:
const outputMyArray = [
{
one: 'A',
two: 'AB'
},
{
one: 'A',
two: 'BC'
},
{
one: undefined,
two: 'CC'
},
The object keys are dynamically generated hence cannot be hardcoded and each object can have same numbers of keys as others.
This I have tried but did not work:
const objectValuesList = myArray.map((obj: any) => Object.values(obj))
const uniqueStrigifiedList = Array.from(new Set( objectValuesList.filter((obj: any) => !obj.includes(undefined)).map((obj: any) => JSON.stringify(obj)) ))
myArray?.filter((obj: any) => !uniqueStrigifiedList?.includes( String(Object.values(obj)) ))
This solution does not seem to be working as it considers all object keys as unique.
答案1
得分: 0
以下是翻译好的内容:
这可以通过一个筛选器来完成:
-
如果没有
one
,-
并且数组中没有具有相同
two
和非未定义one
的其他元素,-
那么它未通过筛选器(被移除)
-
否则,它通过了筛选器(被保留)
-
-
-
否则,它通过了筛选器(被保留)
const myArray = [{one: 'A', two: 'AB'}, {one: undefined, two: 'AB'}, {one: 'A', two: 'BC'}, {one: undefined, two: 'CC'}];
const output = myArray.filter((value) => !value.one ? !myArray.some((other) => other !== value && other.two === value.two && other.one) : true);
console.log(output);
英文:
This should be doable with one filter:
-
If there is no
one
,-
and if there isn't any other element in the array with the same
two
and a non-undefinedone
,-
then it fails the filter (removed)
-
else, it passes (kept)
-
-
-
Otherwise, it passes the filter (kept)
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const myArray=[{one:'A',two:'AB'},{one:undefined,two:'AB'},{one:'A',two:'BC'},{one:undefined,two:'CC'},];
const output = myArray.filter((value) => !value.one ? !myArray.some((other) => other !== value && other.two === value.two && other.one) : true);
console.log(output);
<!-- end snippet -->
答案2
得分: 0
我尝试过这个,它对我有用。
const outputMyArray = myArray.filter((obj, index) => {
if (!obj.one) {
let flag = true;
for (let i = 0; i < myArray.length; i++) {
if (index == i) continue;
if (obj.two == myArray[i].two) flag = false;
}
return flag
} else return true
});
也许这不是最佳实践,但我尝试去帮助。
英文:
I tried this and it worked with me
const outputMyArray = myArray.filter((obj, index) => {
if (!obj.one) {
let flag = true;
for (let i = 0; i < myArray.length; i++) {
if (index == i) continue;
if (obj.two == myArray[i].two) flag = false;
}
return flag
} else return true
});
Maybe it isn't the best practices but I tried to help
答案3
得分: 0
你可以采取两个步骤的方法:
- 获取所有值不为
undefined
的对象,并将这些值存储到一个对象中。 - 检查具有
undefined
的对象,如果没有见过,则将该对象添加到结果数组中。
以下是示例代码:
const data = [{ one: 'A', two: 'AB' }, { one: undefined, two: 'AB' }, { one: 'A', two: 'BC' }, { one: undefined, two: 'CC' }];
const keys = ['one', 'two'];
const result = [];
const seen = Object.fromEntries(keys.map(k => [k, {}]));
const withUndefined = [];
for (const o of data) {
if (keys.every(k => o[k] !== undefined)) {
keys.forEach(k => seen[k][o[k]] = true);
result.push(o);
} else {
withUndefined.push(o);
}
}
for (const o of withUndefined) {
if (keys.some(k => seen[k][o[k]])) continue;
result.push(o);
}
console.log(result);
上述代码实现了你提出的两个步骤。
英文:
You could take a two step approach:
- Get all object with no
undefined
as value and store the values with to an object. - Check the objects with
undefined
and if not seen add this object to the result array.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
data = [{ one: 'A', two: 'AB' }, { one: undefined, two: 'AB' }, { one: 'A', two: 'BC' }, { one: undefined, two: 'CC' }],
keys = ['one', 'two'],
result = [],
seen = Object.fromEntries(keys.map(k => [k, {}])),
withUndefined = [];
for (const o of data) {
if (keys.every(k => o[k] !== undefined)) {
keys.forEach(k => seen[k][o[k]] = true);
result.push(o);
} else {
withUndefined.push(o);
}
}
for (const o of withUndefined) {
if (keys.some(k => seen[k][o[k]])) continue;
result.push(o);
}
console.log(result);
<!-- language: lang-css -->
.as-console-wrapper { max-height: 100% !important; top: 0; }
<!-- end snippet -->
答案4
得分: 0
// 定义用于表示对象形状的类型
const myArray: Array<Record<string, string | undefined>> = [
{ one: 'A', two: 'AB' },
{ one: undefined, two: 'AB' },
{ one: 'A', two: 'BC' },
{ one: undefined, two: 'CC' },
]
const outputMyArray = myArray.filter(obj => {
// 获取每个对象的键
const keys = Object.keys(obj);
// 对于空对象,应该采取什么措施?
if (keys.length === 0) {
return false;
} else {
// 使用 'for of' 循环获取数组中每个对象的每个键值。
for (const key of keys) {
if (obj[key] === undefined) {
// 一旦有一个未定义的键
return false;
}
}
// 所有键都不是未定义的
return true;
}
})
console.log(outputMyArray);
英文:
// Define the type to indicate the shape of the objects
const myArray: Array<Record<string, string | undefined>> = [
{ one: 'A', two: 'AB' },
{ one: undefined, two: 'AB' },
{ one: 'A', two: 'BC' },
{ one: undefined, two: 'CC'},
]
const outputMyArray = myArray.filter(obj => {
// Get the keys for each object
const keys = Object.keys(obj);
// What would you do in the case of empty objects?
if (keys.length === 0) {
return false;
} else {
// Using 'for of' loop to get each key value for each object within the array.
for (const key of keys) {
if (obj[key] === undefined) {
// once there's one undefined key
return false;
}
}
// All the keys were not undefined
return true;
}
})
console.log(outputMyArray);
答案5
得分: 0
在数组中,将数组减少到一个新数组。对于数组中的每个对象,请检查累加器(acc
)中是否存在匹配的对象,如果找到则替换它。如果没有找到匹配的对象,将当前项添加到累加器中。
英文:
Reduce the array to a new array. For each object in the array check for a matching object in the accumulator (acc
), and if found replace it. If not, add the current item to the accumulator:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const { isMatchWith, isUndefined } = _
const data = [{ one: 'A', two: 'AB' }, { one: undefined, two: 'AB' }, { one: 'A', two: 'BC' }, { one: undefined, two: 'CC' }]
// match if values are identical or if the 2nd value is undefined
const isMatchWithUndefined = (o1, o2) =>
isMatchWith(o1, o2, (_, v2) => isUndefined(v2) || undefined)
// find and return the best match (less undefined) and the index
const findMatch = (arr, o1) => {
for(let i = 0; i < arr.length; i++) {
const o2 = arr[i]
if(isMatchWithUndefined(o1, o2)) return [o1, i]
if(isMatchWithUndefined(o2, o1)) return [o2, i]
}
return [null, -1]
}
const result = data.reduce((acc, o) => {
const [match, index] = findMatch(acc, o)
if(match) acc[index] = match // if there's a match set the match at the index
else acc.push(o) // if not add the item to the accumulator
return acc
}, [])
console.log(result)
<!-- language: lang-css -->
.as-console-wrapper { max-height: 100% !important; top: 0; }
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论