简单数组的合并

请添加图片描述
请添加图片描述

<template>
  <div>
    <div>数组1:{{ arry1 }}</div>
    <div>数组2:{{ arry2 }}</div>
    <el-button @click="Cli_union(0)">合并数组</el-button>
    <el-button @click="Cli_union(1)">交集数组</el-button>
    <el-button @click="Cli_union(2)">并集数组</el-button>
  </div>
</template>

<script setup>
let arry1 = [11, 24, 53, 56, 57, 88];
let arry2 = [56, 56, 77, 45, 26, 62, 88];

const union = [...new Set([...arry1, ...arry2])];
const cross = [...new Set(arry1.filter((it) => arry2.includes(it)))];
const diff = union.filter((it) => !cross.includes(it));

//合并数组
function Cli_union(res) {
  if (res == 0) {
    console.log("合并数组", union);
  } else if (res == 1) {
    console.log("数组的交集", cross);
  } else {
    console.log("数组的并集", diff);
  }
}
</script>

多重数组的合并

请添加图片描述

<template>
  <div>
    <div>数组1:{{ arry1 }}</div>
    <div>数组2:{{ arry2 }}</div>
    <div>合并的数组:{{ sumarry }}</div>
    <el-button @click="Btn_CLick">合并数组</el-button>
  </div>
</template>

<script setup>
let arry1 = [1, [2, [3, [4, [5]]]]];
let arry2 = [6, 7, 8, [9, [10]]];
function margeArrays(arrys) {
  let query = [...arrys];
  let result = [];
  while (query.length) {
    const item = query.shift(); 
    if (Array.isArray(item)) {
      query.unshift(...item); 
    } else {
      result.push(item);
    }
  }
  return result;
}

let sumarry = ref();
function Btn_CLick() {
  sumarry.value = margeArrays(arry1).concat(margeArrays(arry2));
  console.log(margeArrays(arry1).concat(margeArrays(arry2)));
}
</script>

小知识

shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。
isArray() 方法用于判断一个对象是否为数组。 如果对象是数组返回 true,否则返回 false。
unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。

Logo

前往低代码交流专区

更多推荐