简体   繁体   English

使用JavaScript在逗号分隔的字符串中查找新值

[英]find new values in comma separated string using Javascript

I have an array 我有一个数组

       obj = ["30890560", "29092960", "28652336", "28642195", "26512957", "26190575", "25465297", "25144372", "23579449"]

and I need to compare it to a comma separated string 我需要将其与逗号分隔的字符串进行比较

     "29092960,28652336,28642195,26512957,26190575,25465297,25144372"

is there a way for me to end up with an new comma separated string such as 有没有办法让我以新的逗号分隔的字符串结尾,例如

       let newList = "30890560,23579449"

The array will always have more values then the string for the comparison. 数组将始终具有比用于比较的字符串更多的值。 This needs to be done using JavaScript inside a Vue.js page so no jQuery. 这需要在Vue.js页面中使用JavaScript来完成,因此不能使用jQuery。

Do I need to split the comma separated string and compare each value in the array? 我是否需要分割逗号分隔的字符串并比较数组中的每个值?

something like 就像是

        ["30890560", "29092960", "28652336", "28642195", "26512957", "26190575", "25465297", "25144372", "23579449"].includes('30890560');

Would a create a loop looking for a false value? 创建循环会寻找错误的值吗? I would need some help to structure the loop. 我需要一些帮助来构造循环。 Thanks 谢谢

 const arr1 = ["30890560", "29092960", "28652336", "28642195", "26512957", "26190575", "25465297", "25144372", "23579449"]; const str = "29092960,28652336,28642195,26512957,26190575,25465297,25144372"; const arr2 = str.split(','); // Convert CSV String to array const res = arr1.filter(v => !arr2.includes(v)); console.log(res) 

String/split MDN 字符串/拆分MDN
Array/filter MDN 阵列/过滤器MDN
Array/includes MDN 阵列/包含MDN

You can JavaScript's split() method to separate the string into an array of strings. 您可以使用JavaScript的split()方法将字符串分成字符串数组。 And then compare both the arrays. 然后比较两个数组。

 var obj = ["30890560", "29092960", "28652336", "28642195", "26512957", "26190575", "25465297", "25144372", "23579449"]; var str = "29092960,28652336,28642195,26512957,26190575,25465297,25144372"; var list = str.split(','); console.log(list); // Loop over two arrays to compare their equality. for (let i = 0; i < list.length; i++) { if (list[i] !== obj[i]) { // Do something. } } 

You can use split, set and filter 您可以使用split, set and filter

 const arr1 = ["30890560", "29092960", "28652336", "28642195", "26512957", "26190575", "25465297", "25144372", "23579449"] const str = "29092960,28652336,28642195,26512957,26190575,25465297,25144372" const arr2 = new Set(str.split(',')) const output = arr1.filter(v => !arr2.has(v)); console.log(output) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM