Get unique string in imacros Javascript - javascript

Suppose I have a string "1,2,1,2,2,3,4", now I want to get unique from this such that My output looks like 1,2,3,4
I have tried with
TAG POS=1 TYPE=div ATTR=class:type-txt<sp>icon-txt&&TXT:* EXTRACT=TXT
SET ag EVAL("'{{!EXTRACT}}'.split('BHK')[0].replace(/(.)\1+/g, '$1');")
PROMPT {{ag}}
This is the link of website from where I extract data
The o\p of "ag" is 1,1,2,1,1,2,3
Is there any way by which it could be solved.
Thanks.

You can do
let str = "1,2,1,2,2,3,4";
let result = Object.keys(str.split(',').reduce((a, b) => (a[b] = true, a), {}));
console.log(result);
Explanation, I used the fact that the keys of an object would be unique, so after splitting the string, I just created an object with those elements as properties, the keys would all be unique.
You can also try
let str = "1,2,1,2,2,3,4";
let result = Array.from(new Set(str.split(',')));
console.log(result);

You can try something like this:
Logic:
Split string using delimiter(,) to get array of values.
Loop over this array.
Concat string to an empty string to create your final string.
Check if the value exists in your final string.
If yes, do not concat.
If no, concat it.
Return this final string.
For ease in manipulation, I have added ,<value> and then displayed string from 1 index,
let str = "1,2,1,2,2,3,4";
let result = str.split(',').reduce(function(p, c){
if(p.indexOf(c) < 0) {
p += ',' + c
}
return p;
}, '');
console.log(result.substring(1));

Using ES6 you can take advantage of the spread operator:
var myString = "1,2,1,2,2,3,4";
var output = [... new Set(myString)] // [1,2,3,4]
If you want the output to be a string:
output.join(); // "1,2,3,4"

Related

JS Array.splice return original Array and chain to it

I have a string with values like this a,b,c,d and want to remove a specific letter by index
So here is what I did str.split(',').splice(1,1).toString() and this is (obviously) not working since splice is returning the values removed not the original array
Is there any way to do the above in a one liner?
var str = "a,b,c,d";
console.log(str.split(',').splice(1,1).toString());
Thanks in advance.
You can use filter and add condition as index != 1.
var str = "a,b,c,d";
console.log(str.split(',').filter((x, i) => i != 1).toString());
Another strange solution. Destructure the array, remove the unwanted index, get an object and join the values of it.
var string = "a,b,c,d",
{ 1: _, ...temp } = string.split(',')
console.log(Object.values(temp).join(','));
The alternate way using regex replace
var str = "a,b,c,d";
console.log(str.replace(/,\w+/, ''))
Splice works in place, so oneliner is
const arr = "a,b,c,d".split(','); arr.splice(1,1); console.log(arr.toString());
If you want an string in a oneliner, you have to hardcode the index in a filter
console.log("a,b,c,d".split(',').filter((item, i) => i != 1).toString())
Or two slices (not performant at all)
const arr = "a,b,c,d".split(',')
console.log([...arr.slice(0,1),...arr.slice(2)].toString())

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

Chaining array and string methods in javascript

I try to chain some array and string methods but it doesn't work. It'd be great if anyone could explain to me why a function such as this doesn't work:
const scream = text => text.split('').push('!').join('').toUpperCase()
You could use Array#concat to return an array with another value instead of Array#push, which returns the new length, but is not part of a fluent interface for a later joining (which needs an array).
const scream = text => text.split('').concat('!').join('').toUpperCase();
console.log(scream('hi'));
Push doesn't return the array. Here's an example that demonstrates what's happening with push, and shows another way to do it:
const scream = text => text.split('').push('!').join('').toUpperCase()
const test = ['a', 'b', 'c'];
const result = test.push('!')
console.log(result)
const newScream = text => [
...text,
'!'
].join('').toUpperCase()
newScream('hello')
console.log(newScream('hello'))
If you want to add 1 ! at the end:
const scream = text => text.split('').concat('!').join('').toUpperCase();
If you want to add it after each letter:
const scream = text => text.split('').map(e => e + '!').join('').toUpperCase();
The push don't return array, so join is not called on array in your case.
If you want to add character/string at the end of string use concat(<ch>) function. If you want to change case to upper then use toUpperCase() function.
Or
Simply you can use + operator to concat two strings and append ! to it.
var str = "Hello World";
var res = str.toUpperCase().concat("!");
var result = (str + '!').toUpperCase();
console.log(res);
console.log(result);

How do I convert an array inside an array to a string?

I'm new to programming. I am coding with javascript.
I want to convert an array with 3 arrays inside it to one single string and have spaces between each of the different arrays.
I want to turn this:
var myArray = [['example'], ['text'], ['hm']]
Into this:
var myString = 'example text hm'
I think you want that to be an array with []. If that's the case, this is a good use for reduce() combined with join() which will progressively build a concatenated array which you can then join:
let myArray = [['example'], ['text', 'text2'], ['hm']]
let str = myArray.reduce((all, arr) => all.concat(arr)).join(' ')
console.log(str)
Use nested for-each loops.
myString = "";
for each (row in myArray){
for each (column in row){
myString = myString + column;
}
}
In this specific case, you can use the standard Array.join(). This will invoke the sub-array's .toString() method. Usually it returns a string of the items, separated by commas, but Since you've got only a single item in each sub-array, you'll get that item in a string.
const myArray = [['example'], ['text'], ['hm']]
const result = myArray.join(' ')
console.log(result)
You can join them together using Array.join(' ')
const sentence = myArray.join(' ')
will return "example text hm"
The speech marks separated will keep the words separate and stop them joining together. If they are together it will join all the strings "exampletexthm"
I would also suggest that you use const or let instead of var. It can cause some issues. Article to look at

A nested array of string to number

I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]
The first step would be to create valid JSON from your string.
If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.
A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":
const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";
// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]";
// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);
// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);
// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));
You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).
let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);
Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :
let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);
Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.
This thread shows you how to loop through an array of strings to convert it to an array of floats.
i hope this will work..
var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]
var output = [];
input.forEach(o => {
o.forEach(s => parseFloat(s))
output.push(o);
})
console.log(output);

Categories

Resources