按对象数组中的嵌套值排序

时间:2018-10-09 18:46:55

标签: javascript sorting

我正在尝试根据对象数组是否包含嵌套值对其进行排序。我弄乱了使用_.sortBy,进行归约和排序,但实际上没有任何工作对我有用。

这是我的数据集:

const impacts = [{

impactAreas: [{
      name: "development"
    }, {
      name: "education"
    }],
  },
  {

    impactAreas: [{
      name: "education"
    }],
  },
  {
    impactAreas: [{
      name: "development"
    }, {
      name: "politics"
    }],
  },
  {
    impactAreas: [{
      name: "politics"
    }, {
      name: "education"
    }]
  }
]

function getImpacts(impacts) {
  impacts.forEach(
    impact => impact.impactAreas.reduce((acc, impactArea) => {
      if (impactArea.name === 'politics') {
        console.log(yes)
        return [impactArea, ...acc]
      }
      return [...acc, impactArea];
    }, [])
  )
}

在此示例中,我试图按对象是否包含“政治”但未返回返回值进行排序。

这是我的jfiddle示例:https://jsfiddle.net/ycrpaLn5/1/

谢谢!

2 个答案:

答案 0 :(得分:0)

假设您要将所有带有politics的项目移到顶部,那么您将对嵌套数组使用支票,并将支票的差额作为排序的返回值。

var impacts = [{ impactAreas: [{ name: "development" }, { name: "education" }] }, { impactAreas: [{ name: "education" }] }, { impactAreas: [{ name: "development" }, { name: "politics" }] }, { impactAreas: [{ name: "politics" }, { name: "education" }] }],
    POLITICS = ({ name }) => name === 'politics';

impacts.sort(({ impactAreas: a }, { impactAreas: b }) =>
    b.some(POLITICS) - a.some(POLITICS));

console.log(impacts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

如果您只关心顶部的政治,则将数组简化为一个包含政治的数组(第一个),一个不包含政治的数组,然后将它们连接起来:

const impacts = [{ impactAreas: [{ name: "development" }, { name: "education" }] }, { impactAreas: [{ name: "education" }] }, { impactAreas: [{ name: "development" }, { name: "politics" }] }, { impactAreas: [{ name: "politics" }, { name: "education" }] }];

const hasPolitics = ({ impactAreas }) => 
  impactAreas.some(({ name }) => name === 'politics');

const result = [].concat(...impacts.reduce((r, o) => {
  r[hasPolitics(o) ? 0 : 1].push(o);
  
  return r;
}, [[], []]));

console.log(result);

如果您不需要保留原始顺序,则可以在减少累加器的开头添加具有政治意义的项目:

const impacts = [{ impactAreas: [{ name: "development" }, { name: "education" }] }, { impactAreas: [{ name: "education" }] }, { impactAreas: [{ name: "development" }, { name: "politics" }] }, { impactAreas: [{ name: "politics" }, { name: "education" }] }];

const hasPolitics = ({ impactAreas }) => 
  impactAreas.some(({ name }) => name === 'politics');

const result = impacts.reduce((r, o) =>
  hasPolitics(o) ? [o, ...r] : [...r, o]
, []);

console.log(result);