javascript在项目中的算法(二)

该文展示了一系列JavaScript函数,用于处理数据结构。包括从嵌套对象中获取叶子节点值,按条件筛选对象数组,获取指定区间的时间数据,过滤并转换键值对,以及计算数组中的中位数和最小值。示例代码详细展示了这些功能的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.获取叶子节点和最外层的节点

function getUniqueValuesByKey(objArr, key) {
  let stack = objArr;
  const values = [];
  while (stack.length) {
    const obj = stack.pop();
    const value = obj?.[key];
    if (value !== undefined) {
      values.unshift(value);
    }
    stack = stack.concat(Object.values(obj ?? {}).filter(
      prop => typeof prop === "object" && prop !== null
    ));
  }
  if (values.length === 0) {
    return [];
  }
  if (values[0] === values[values.length - 1]) {
    return [values[0]];
  }
  return [values[0], values[values.length - 1]];
}

var objArr = [
  {
    name: "Tom",
    age: 25,
    address: {
      city: "Beijing",
      street: "Main Street"
    },
    interests: ["reading", "music"]
  },
  {
    name: "Jerry",
    age: 30,
    address: {
      city: "Shanghai",
      street: "Second Street"
    },
    interests: ["swimming"]
  },
  {
    name: "Alice",
    age: 28,
    address: {
      city: "Guangzhou",
      street: "Third Street"
    },
    interests: ["traveling", "photography"]
  }
];

var cities = getUniqueValuesByKey(objArr, "city");

console.log(cities); // 输出 [ "Beijing", "Guangzhou" ]

2.按要求取出区间的值

const getFeatureMonths = (gap = 12) => {
  const currYear = moment().format('YYYY');
  const nextYear = moment().subtract(-gap, 'month').format('YYYY'); // 1年后

  const currYearList = [];
  const nextYearList = [];

  for (let i = 0; i < gap; i++) {
    const year = moment().subtract(-i, 'month').format('YYYY');
    const month = moment().subtract(-i, 'month').format('MM');
    const timeData = {
      value: `${year}${month}`,
    };

    if (year > currYear) {
      nextYearList.push(timeData);
    } else {
      currYearList.push(timeData);
    }
  }

  return [
    ...nextYearList,
    ...currYearList,
  ];
}
const arr = [{value:'202301'},{value:'202302'},{value:'202303'},{value:'202304'}];
const indexes = [2, 4];
const result = arr.slice(indexes[0]-1, indexes[1]).map(item => item.value);

console.log(result); // ['202302', '202303', '202304']
const a = [{label: 7}, {label: 8}, {label: 9}, {label: 10}];
const b = [{label: 1}, {label: 2}, {label: 3}, {label: 4}, {label: 5}, {label: 6}];
const x = [5];

const result = (a.some(i => x.includes(i.label)) ? a.filter(i => i.label >= x) : (b.some(i => x.includes(i.label)) ? b.filter(i => i.label >= x) : []));

console.log(result);

3.获取对象数组中满足条件的值

const d= [
  {
    id: 1,
    name: 'John',
    age: 30,
    children: [
      {
        id: 2,
        name: 'Jane',
        age: 6
      },
      {
        id: 3,
        name: 'Bob',
        age: 15,
        children: [
          {
            id: 4,
            name: 'Alice',
            age: 2
          }
        ]
      }
    ]
  },
  {
    id: 5,
    name: 'Mary',
    age: 25
  }
];
function getChildrenIdsAndNames(data,num) {
  const res = [];
  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item.children) {
      res.push(...getChildrenIdsAndNames(item.children,num));
    }
    if (item.age <= num) {
      res.push({
        id: item.id,
        name: item.name
      });
    }
  }
  return res;
}

const result = getChildrenIdsAndNames(data,10);
console.log(result);
const getChildrenIdsAndNames = (data, num) => data.flatMap(item => [
  ...(item.children ? getChildrenIdsAndNames(item.children, num) : []),
  ...(item.age <= num ? [{ id: item.id, name: item.name }] : [])
]);
const result = getChildrenIdsAndNames(data,10);
console.log(result);

4.将键值对,转成对象数组

const obj = {
  name: 'Alice',
  age: 25,
  gender: 'female'
};

const arr = Object.entries(obj).map(([key, value]) => ({ key, value }));

console.log(arr);
// Output: [{key: 'name', value: 'Alice'}, {key: 'age', value: 25}, {key: 'gender', value: 'female'}]
const obj = {
  name: 'Alice',
  age: 25,
  gender: 'female'
};

const arr = Object.entries(obj).map(([key, value]) => ({ key, value }));

console.log(arr);
// Output: [{key: 'name', value: 'Alice'}, {key: 'age', value: 25}, {key: 'gender', value: 'female'}]

5.过滤掉对象中为null的键值对,返回由键组成的数组

const obj = {
  key1: "value1",
  key2: null,
  key3: "value3",
  key4: ""
};

const filteredKeys = Object.entries(obj)
  .filter(([key, value]) => value !== null && value !== undefined && value !== "")
  .map(([key, value]) => key);

console.log(filteredKeys);

6.取出中位数和最小数

const arr = [
    {"name": "商品1", "price": 100, "image": {"url": "image5.jpg"}},
    {"name": "赠品1", "price": 0},
    {"name": "商品2", "price": 200, "image": {"url": "image2.jpg"}},
    {"name": "赠品2", "price": 0, "image": {"url": "image3.jpg"}},
    {"name": "商品3", "price": 150, "image": {"url": "image1.jpg"}},
    {"name": "配件1", "price": 50}
];

function getCengObjects(arr) {
  // 过滤掉带有赠或配关键字的对象
  const filteredArr = arr.filter(obj => !obj.name.includes("赠") && !obj.name.includes("配"));
   
  // 按价格从小到大排序
  const sortedArr = filteredArr.sort((a, b) => a.price - b.price);
    
    // 取出最小值
const minValue = sortedArr.reduce((min, obj) => min.price < obj.price ? min : obj);
console.log("最小值:", minValue);
// 计算中位数
let medianObjs;
const midIndex1 = Math.floor(sortedArr.length / 2);
const midIndex2 = midIndex1 - 1;

if (sortedArr.length % 2 === 0) {
    // 偶数个元素
    if (sortedArr[midIndex1].price === sortedArr[midIndex2].price) {
        // 如果价格相同,则选择有图片的对象
        medianObjs = [sortedArr[midIndex1], sortedArr[midIndex2]].filter(obj => obj.image && obj.image.url !== "");
        if (medianObjs.length === 0) {
            medianObjs = [sortedArr[midIndex2]];
            medianObjs[0].image = {"url": "default.jpg"};
        }
    } else {
        // 选择价格最小的对象
        medianObjs = [sortedArr[midIndex1], sortedArr[midIndex2]].sort((a, b) => a.price - b.price);
    }
} else {
    // 奇数个元素
    medianObjs = [sortedArr[midIndex1]];
}

  
}
getCengObjects(arr);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值