您现在的位置是:群英 > 开发技术 > web开发
新手可以参考学习的JS数组操作实例有哪些
Admin发表于 2022-09-06 17:48:48349 次浏览
这篇文章给大家分享的是“新手可以参考学习的JS数组操作实例有哪些”,文中的讲解内容简单清晰,对大家学习和理解有一定的参考价值和帮助,有这方面学习需要的朋友,接下来就跟随小编一起学习一下“新手可以参考学习的JS数组操作实例有哪些”吧。

   

随机排序

1、生成随机数

遍历数组,每次循环都随机一个在数组长度范围内的数,并交换本次循环的位置和随机数位置上的元素

function randomSort1(arr) {
  for (let i = 0, l = arr.length; i < l; i++) {
    let rc = parseInt(Math.random() * l)
    // 让当前循环的数组元素和随机出来的数组元素交换位置
    const empty = arr[i]
    arr[i] = arr[rc]
    arr[rc] = empty
  }
  return arr
}

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 下面两次的结果肯定是不一样的;
console.log(randomSort1(arr1))
console.log(randomSort1(arr1))

2、生成新数组

  • 申明一个新的空数组,利用 while 循环,如果数组长度大于 0,就继续循环;

  • 每次循环都随机一个在数组长度范围内的数,将随机数位置上的元素 push 到新数组里,

  • 并利用 splice(对 splice 不太理解的同学可以看这里)截取出随机数位置上的元素,同时也修改了原始数组的长度;

function randomSort2(arr) {
  var mixedArr = []
  while (arr.length > 0) {
    let rc = parseInt(Math.random() * arr.length)
    mixedArr.push(arr[rc])
    arr.splice(rc, 1)
  }
  return mixedArr
}
// 例子
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(randomSort2(arr1))

3、 arr.sort

  • 如果 compareFunction(a, b)的返回值 小于 0 ,那么 a 会被排列到 b 之前;

  • 如果 compareFunction(a, b)的返回值 等于 0 ,那么 a 和 b 的相对位置不变;

  • 如果 compareFunction(a, b)的返回值 大于 0 ,那么 b 会被排列到 a 之前;

function randomSort3(arr) {
  arr.sort(function (a, b) {
    return Math.random() - 0.5
  })
  return arr
}
// 例子
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(randomSort3(arr1))

数组对象排序

1、单个属性排序

function compare(property) {
  return function (a, b) {
    let value1 = a[property]
    let value2 = b[property]
    return value1 - value2
  }
}

let arr = [
  { name: 'zopp', age: 10 },
  { name: 'gpp', age: 18 },
  { name: 'yjj', age: 8 },
]

console.log(arr.sort(compare('age')))

2、多个属性排序

function by(name, minor) {
  return function(o, p) {
    let a, b
    if (o && p && typeof o === 'object' && typeof p === 'object') {
      a = o[name]
      b = p[name]
      if (a === b) {
        return typeof minor === 'function' ? minor(o, p) : 0
      }
      if (typeof a === typeof b) {
        return a < b ? -1 : 1
      }
      return typeof a < typeof b ? -1 : 1
    } else {
      thro('error')
    }
  }
},

数组扁平化

1、调用 ES6 中的 flat 方法

ary = arr.flat(Infinity)

console.log([1, [2, 3, [4, 5, [6, 7]]]].flat(Infinity))

2、普通递归

let result = []
let flatten = function (arr) {
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i]
    if (Array.isArray(arr[i])) {
      flatten(item)
    } else {
      result.push(item)
    }
  }
  return result
}

let arr = [1, 2, [3, 4], [5, [6, 7]]]
console.log(flatten(arr))

3、利用 reduce 函数迭代

function flatten(arr) {
  return arr.reduce((pre, cur) => {
    return pre.concat(Array.isArray(cur) ? flatten(cur) : cur)
  }, [])
}

let arr = [1, 2, [3, 4], [5, [6, 7]]]
console.log(flatten(arr))

4、扩展运算符

function flatten(arr) {
  while (arr.some((item) => Array.isArray(item))) {
    arr = [].concat(...arr)
  }
  return arr
}

let arr = [1, 2, [3, 4], [5, [6, 7]]]
console.log(flatten(arr))

数组去重

1、利用数组的 indexOf 下标属性来查询

function unique(arr) {
  var newArr = []
  for (var i = 0; i < arr.length; i++) {
    if (newArr.indexOf(arr[i]) === -1) {
      newArr.push(arr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

2、先将原数组排序,在与相邻的进行比较,如果不同则存入新数组。

function unique(arr) {
  var formArr = arr.sort()
  var newArr = [formArr[0]]
  for (let i = 1; i < formArr.length; i++) {
    if (formArr[i] !== formArr[i - 1]) {
      newArr.push(formArr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

3、利用对象属性存在的特性,如果没有该属性则存入新数组。

function unique(arr) {
  var obj = {}
  var newArr = []
  for (let i = 0; i < arr.length; i++) {
    if (!obj[arr[i]]) {
      obj[arr[i]] = 1
      newArr.push(arr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

4、利用数组原型对象上的 includes 方法。

function unique(arr) {
  var newArr = []
  for (var i = 0; i < arr.length; i++) {
    if (!newArr.includes(arr[i])) {
      newArr.push(arr[i])
    }
  }
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

5、利用数组原型对象上的 filter 和 includes 方法。

function unique(arr) {
  var newArr = []
  newArr = arr.filter(function (item) {
    return newArr.includes(item) ? '' : newArr.push(item)
  })
  return newArr
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

6、利用 ES6 的 set 方法。

function unique(arr) {
  return Array.from(new Set(arr)) // 利用Array.from将Set结构转换成数组
}
console.log(unique([1, 1, 2, 3, 5, 3, 1, 5, 6, 7, 4]))

根据属性去重

方法一

function unique(arr) {
  const res = new Map()
  return arr.filter((item) => !res.has(item.productName) && res.set(item.productName, 1))
}

方法二

function unique(arr) {
  let result = {}
  let obj = {}
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i].key]) {
      result.push(arr[i])
      obj[arr[i].key] = true
    }
  }
}

交集/并集/差集

1、includes 方法结合 filter 方法

let a = [1, 2, 3]
let b = [2, 4, 5]

// 并集
let union = a.concat(b.filter((v) => !a.includes(v)))
// [1,2,3,4,5]

// 交集
let intersection = a.filter((v) => b.includes(v))
// [2]

// 差集
let difference = a.concat(b).filter((v) => !a.includes(v) || !b.includes(v))
// [1,3,4,5]

2、ES6 的 Set 数据结构

let a = new Set([1, 2, 3])
let b = new Set([2, 4, 5])

// 并集
let union = new Set([...a, ...b])
// Set {1, 2, 3, 4,5}

// 交集
let intersect = new Set([...a].filter((x) => b.has(x)))
// set {2}

// a 相对于 b 的)差集
let difference = new Set([...a].filter((x) => !b.has(x)))
// Set {1, 3}

数组求和

1、万能的 for 循环

function sum(arr) {
  var s = 0
  for (var i = arr.length - 1; i >= 0; i--) {
    s += arr[i]
  }
  return s
}

sum([1, 2, 3, 4, 5]) // 15

2、递归方法

function sum(arr) {
  var len = arr.length
  if (len == 0) {
    return 0
  } else if (len == 1) {
    return arr[0]
  } else {
    return arr[0] + sum(arr.slice(1))
  }
}

sum([1, 2, 3, 4, 5]) // 15

3、ES6 的 reduce 方法

function sum(arr) {
  return arr.reduce(function (prev, curr) {
    return prev + curr
  }, 0)
}

sum([1, 2, 3, 4, 5]) // 15

类数组转化

1、Array 的 slice 方法

let arr = Array.prototype.slice.call(arguments)

2、ES6 的 Array.from()

let arr = Array.from(arguments)

3、扩展运算符...

let arr = [...arguments]

数组上下移动

function swapItems(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0]
  return arr
}

function up(arr, index) {
  if (index === 0) {
    return
  }
  this.swapItems(arr, index, index - 1)
}

function down(arr, index) {
  if (index === this.list.length - 1) {
    return
  }
  this.swapItems(arr, index, index + 1)
}

数组转化为树形结构

将如下数据转化为树状结构

let arr = [
  {
    id: 1,
    name: '1',
    pid: 0,
  },
  {
    id: 2,
    name: '1-1',
    pid: 1,
  },
  {
    id: 3,
    name: '1-1-1',
    pid: 2,
  },
  {
    id: 4,
    name: '1-2',
    pid: 1,
  },
  {
    id: 5,
    name: '1-2-2',
    pid: 4,
  },
  {
    id: 6,
    name: '1-1-1-1',
    pid: 3,
  },
  {
    id: 7,
    name: '2',
  },
]

实现方法

function toTree(data, parentId = 0) {
  var itemArr = []
  for (var i = 0; i < data.length; i++) {
    var node = data[i]
    if (node.pid === parentId) {
      var newNode = {
        ...node,
        name: node.name,
        id: node.id,
        children: toTree(data, node.id),
      }
      itemArr.push(newNode)
    }
  }
  return itemArr
}

console.log(toTree(arr))

以上就是关于新手可以参考学习的JS数组操作实例有哪些的介绍,本文内容仅供参考,有需要的朋友可以借鉴了解看看,希望对大家学习或工作,想要了解更多欢迎关注群英网络,小编每天都会为大家更新不同的知识。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

标签: JS数组
相关信息推荐
2022-04-26 14:23:23 
摘要:在我们日常的开发中,Redis是很常用的,常用的语言都有Redis的API,现在就来分享一下Redis的.NET C#写法和用法,下面开始介绍Redis在C#中的使用。在使用之前一点要安装和添加NuGet包 StackExchange.Redis (.net framework的环境最少是4.5),否则会报错。
2022-08-11 17:14:22 
摘要:这篇文章主要介绍了Python中的time模块和calendar模块,在Python中对时间和日期的处理方式有很多,其中转换日期是最常见的一个功能。Python中的时间间隔是以秒为单位的浮点小数。下面来看看文章具体内容的介绍,需要的朋友可以参考一下,希望对你有所帮助
2022-04-29 16:43:20 
摘要:这篇文章主要介绍了C++浮点数类型,浮点数是C++的第二组基本类型,它能够表示带小数部分的数字。不仅如此,浮点数的范围也比int更大,可以表示更大范围的数字。下面来我们大家一起来学习学习内容
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部