如何实现map而不是for循环

时间:2017-04-16 19:18:13

标签: javascript arrays

我有两个数组(from datetime import datetime, timedelta from django.db import models class MyModel(models.Model): date = models.DateField() # the below method will NOT work if auto_now/auto_now_add are set to True def save(self, *args, **kwargs): # count how many objects are already saved with the date this current object is saved date_gte_count = MyModel.objects.filter(date__gte=self.date).count() if date_gte_count: # there are some objects saved with the same or greater date. Increase the day by this number. self.date += timedelta(days=date_gte_count) # save object in db super().save(*args, **kwargs) req[])需要进行比较,差异应该显示在日志中。为此,我使用for循环,但我想用map来解决这个问题。

注意:首先需要对两个数组进行排序。

res[]

如何使用map使用某些属性(如id或name)对两个数组进行排序,然后在匹配失败时将两个数组和打印错误与值进行比较?

1 个答案:

答案 0 :(得分:0)

要对数组进行排序,请使用Array.sort对数组进行排序。你传递一个排序函数。 sort函数有两个参数(a,b),如果a低于b则返回-1,如果相同则返回0,如果a大于b则返回1

const arr = "akjdfgeknskhg".split(""); // create an array of characters
arr.sort((a,b)=> a < b ? -1 : a > b ? 1 : 0);

要创建一个匹配报告的数组,您可以使用map获取arr中每个项目的一对一地图。为两个数组执行此操作,以便首次检查匹配和不匹配。对于第二个你不需要报告匹配,因为已经完成了所以只做不匹配的并传递一个空的,未定义的空字符串,这无关紧要。

然后过滤掉空值,你就完成了。

   //
    const arr1 = [1,2,5,67,8,4,32,392];
    const arr2 = [1,2,8,4,32,392,76,34,2,44];
    const resArr = [
        ...arr1.map(item => item + (arr2.includes(item) ? " arr1 matched arr2. " : " arr1 unmatched")),
        ...arr2.map(item => !arr1.includes(item) ? item + " arr2 unmatched. " : "")
    ].filter(item => item !== "");
    console.log(resArr);