找到唯一的对象数组,动态考虑未定义的值。

huangapple go评论55阅读模式
英文:

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'
 }
]

这段代码描述了一个数组和所需的格式转换,其中如果oneundefined,但在另一个对象中存在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-undefined one,

      • 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:&#39;A&#39;,two:&#39;AB&#39;},{one:undefined,two:&#39;AB&#39;},{one:&#39;A&#39;,two:&#39;BC&#39;},{one:undefined,two:&#39;CC&#39;},];

const output = myArray.filter((value) =&gt; !value.one ? !myArray.some((other) =&gt; other !== value &amp;&amp; other.two === value.two &amp;&amp; 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) =&gt; {
    if (!obj.one) {
        let flag = true;
        for (let i = 0; i &lt; 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

你可以采取两个步骤的方法:

  1. 获取所有值不为undefined的对象,并将这些值存储到一个对象中。
  2. 检查具有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:

  1. Get all object with no undefined as value and store the values with to an object.
  2. 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 =&gt; o[k] !== undefined)) {
        keys.forEach(k =&gt; seen[k][o[k]] = true);
        result.push(o);
    } else {
        withUndefined.push(o);
    }
}

for (const o of withUndefined) {
    if (keys.some(k =&gt; 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&lt;Record&lt;string, string | undefined&gt;&gt; = [
    { one: &#39;A&#39;, two: &#39;AB&#39; },
    { one: undefined, two: &#39;AB&#39; },
    { one: &#39;A&#39;, two: &#39;BC&#39; },
    { one: undefined, two: &#39;CC&#39;},
]

const outputMyArray = myArray.filter(obj =&gt; {
    // 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 &#39;for of&#39; loop to get each key value for each object within the array.
        for (const key of keys) {
            if (obj[key] === undefined) {
                // once there&#39;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: &#39;A&#39;, two: &#39;AB&#39; }, { one: undefined, two: &#39;AB&#39; }, { one: &#39;A&#39;, two: &#39;BC&#39; }, { one: undefined, two: &#39;CC&#39; }]

// match if values are identical or if the 2nd value is undefined
const isMatchWithUndefined = (o1, o2) =&gt; 
  isMatchWith(o1, o2, (_, v2) =&gt; isUndefined(v2) || undefined)

// find and return the best match (less undefined) and the index
const findMatch = (arr, o1) =&gt; {
  for(let i = 0; i &lt; 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) =&gt; {  
  const [match, index] = findMatch(acc, o)
  
  if(match) acc[index] = match // if there&#39;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 -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js&quot; integrity=&quot;sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==&quot; crossorigin=&quot;anonymous&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月21日 02:21:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定