ES6 - Reorder an Array with respect to an Object - javascript

I have an array which is like :
const my_array = [
"S T"
"O P"
"Lend"
"GT"
"CT"
"AC"
];
and an object according to which this array is being reordered:
const AN_ORDER = {
'Lend': 1,
'C T': 2,
'S T': 3,
'AC': 4,
'O P': 5
};
for which there is already a solution done as
//keys and sortBy from Lodash
const new_array = keys(my_array);
return sortBy(new_array, ar => AN_ORDER[ar] || Number.MAX_SAFE_INTEGER);
this yields me new array as:
["Lend", "AC", "O P", "S T", "GT", "C T"]
I tried looking into documentation of this usage, but I do not understand the idea of second argument being used here in sortBy.
Now my need is to reorder the my_array in below sequence:
['Lend', 'C T', 'S T', 'GT', 'AC', 'O P']
Please help me understand the implementation and suggest a way I can reorder in the same logic.

Your key 'G T' is not in object 'AN_ORDER' so my output will look different than yours. but it's working right.
const myArray = [
'S T',
'O P',
'Lend',
'GT',
'C T',
'AC'
];
const AN_ORDER = {
'Lend': 1,
'C T': 2,
'S T': 3,
'AC': 4,
'O P': 5
};
const sortedCollection = _.sortBy(myArray, item => {
return AN_ORDER[item];
});

You have add array in second argument, here you can mention callback function or property name.
Here is the working solution
const my_array = [
"S T",
"O P",
"Lend",
"GT",
"C T",
"AC"
];
var AN_ORDER = {
"Lend": 1,
"C T": 2,
"S T": 3,
"AC": 4,
"O P": 5
};
console.log(_.sortBy(my_array, [a => {
return (AN_ORDER[a] || Number.MAX_SAFE_INTEGER);
}]));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>

Not sure what AN_ORDER represents, as there isn't enough information on what it represents exactly.
Uses the keys in AN_ORDER in the final array, because the specified output above uses that. Strips spaces before searching for matching keys, using a Set to search if they exist, and using an offset of 0.5 to insert non-existing keys into AN_ORDER for sorting.
const my_array = [
"S T",
"O P",
"Lend",
"GT",
"CT",
"AC"
];
const AN_ORDER = {
'Lend': 1,
'C T': 2,
'S T': 3,
'AC': 4,
'O P': 5
};
const keys = new Set(Object.keys(AN_ORDER).map(x=>x.replace(/\s/g,'')))
my_array.forEach( (x,i)=>!keys.has(x.replace(/\s/g,'')) && (AN_ORDER[x]=i+0.5) )
my_obj = _.sortBy(Object.entries(AN_ORDER), ([,x])=>x).map(([x,])=>x)
console.log(my_obj);
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>

Related

Sorting javascript object by number (value), then abc order by string (key)

I'm having trouble sorting through this array in a way that's in the title where words are the keys and value is the count.
const words = {
"be": 3,
"a": 5,
"an": 3
}
Desired out put would be:
{
"a": 5,
"an": 3,
"be": 3
}
Object.entries(wordCount).sort(([, a], [, b]) => b - a)
But I don't know how I would sort items with the same value in abc order :'(
Using the clever technique found in another answer:
const words = {
"be": 3,
"a": 5,
"an": 3
}
const sortedEntries = (o) =>
Object.entries(words)
.sort(([k1, v1], [k2, v2]) =>
v2 - v1 || k1.localeCompare(k2))
console.log(sortedEntries(words))

Merge array items and object values by common key/index

I have an array of arrays like this:
let a = [
['A', 'B'], // 1 in the object
['C'], // 2 in the object
];
and I have an object of objects like this:
let b = {
5:{
1: "i was send to earth. i was send to her.",
2: "to mars",
3: { reference: "to moon.", expectSt: "to mars. i love it." },
},
};
As you see there are two patterns in the object. the pattern like 1 and 2 and the pattern like 3.
I just want to add sentences in 1 to the first array inside let a and sentences in 2 to the second array inside let a and so on...
and if the pattern was like 3 then I just want to add sentences of expectSt and ignore reference
The result should be this:
let a = [
['A', 'B', 'i was send to earth', 'i was send to her'], // 1 in the object
['C', 'to mars'], // 2 in the object
['to mars', 'i love it'], // there is a 3 i the object so we added this
];
I have tried a lot but I think I need a hand to solve this.
Would something as simple as that work for you?
let a = [['A','B'],['C'],],
b = {5:{1:"i was send to earth. i was send to her.",2:"to mars",3:{reference:"to moon.",expectSt:"to mars. i love it."},},}
Object
.values(b[5])
.forEach((value,key) =>
a[key] = [
...(a[key]||[]),
...(value.expectSt || value)
.toLowerCase()
.replace(/\.$/,'')
.split('. ')
]
)
console.log(a)
.as-console-wrapper{min-height:100%;}
let a = [
['A', 'B'], // 1 in the object
['C'], // 2 in the object
];
let b = {
5:{
1: "i was send to earth. i was send to her.",
2: "to mars",
3: { reference: "to moon.", expectSt: "to mars. i love it." },
},
};
Object.values(b).forEach(element => {
Object.keys(element).forEach(e => {
console.log(element[e]);
if(e === '1') a[0].push(...element[e].split('.').filter(a => a !== '').map(a => a.trim()));
else if(e === '2') a[1].push(...element[e].split('.').filter(a => a !== '').map(a => a.trim()));
else if(e === '3') {
if(a.length < 3) a.push([]);
a[2].push(...element[e].expectSt.split('.').filter(a => a !== '').map(a => a.trim()))
}
})
});
console.log(a);

Removing Duplicates in Arrays

I am trying to pass a function that removes duplicates from an array. It should handle strings, object, integers as well. In my code so far I am showing that it will handle strings but nothing else. How can Imake this function universalto handle numbers,handle arrays,handle objects, and mixed types?
let unique = (a) => a.filter((el, i ,self) => self.indexOf(el) ===i);
In this function I hav unique() filtering to make a new array which checks the element and index in the array to check if duplicate. Any help would be appreciated.
i think the first you should do is to sort the array ( input to the function ). Sorting it makes all the array element to be ordered properly. for example if you have in an array [ 1, 3, 4, 'a', 'c', 'a'], sorting this will result to [ 1 , 3 , 4, 'a', 'a' , 'c' ], the next thing is to filter the returned array.
const unique = a => {
if ( ! Array.isArray(a) )
throw new Error(`${a} is not an array`);
let val = a.sort().filter( (value, idx, array) =>
array[++idx] != value
)
return val;
}
let array = [ 1 , 5, 3, 2, "d", "q", "b" , "d" ];
unique(array); // [1, 2, 3, 5, "b", "d", "q"]
let obj = { foo: "bar" };
let arraySize = array.length;
array[arraySize] = obj;
array[arraySize++] = "foo";
array[arraySize++] = "baz";
array[arraySize++] = obj;
unique(array); // [1, 2, 3, 5, {…}, "b", "baz", "d", "foo", "hi", "q"]
it also works for all types, but if you pass in an array literal with arrays or objects as one of its element this code will fail
unique( [ "a", 1 , 3 , "a", 3 , 3, { foo: "baz" }, { foo: "baz" } ] ); // it will not remove the duplicate of { foo: "baz" } , because they both have a different memory address
and you should also note that this code does not return the array in the same order it was passed in , this is as a result of the sort array method
Try using sets without generics. You can write a function as
Set returnUnique(Object array[]) {
Set set=new HashSet();
for (Object obj:array) {
set.add(obj);
}
return set;
}

Iterate over integer in javascript where each value equals a single digit

I would like to use the $.each() loop to iterate over digits in an integer.
The integer is produced as the index of another array, though I'm not sure that this makes a difference.
Javascript
var words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];
var numbers = [];
$.each(words, function(i,word) {
$.each(i, function(index,value) {
$(numbers).append(value);
});
});
I would like the array numbers to equal the following array:
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1 ]
Where the last four entries, [ ... 1, 0, 1, 1 ] are generated through iteration over the indexes for the entries [ ... "than", "ten." ] in the words array.
let words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];
let numbers = words.map((w, i) => i.toString().split('').map(Number)) //map into array of digits
numbers = Array.prototype.concat.call(...numbers); //concat them all
console.log(numbers);

Javascript create array with fixed value but matching column amount from another array

I have an array which is built from data dynamically, so it can change.
It's basically this:
["t1", "something", "bird", "dog", "cow", "fish"]
What I need to do is to count how many of them there are and create another array with the same amount of columns but all with the value of 1.
For example, if the array is:
["bird", "dog", "cow", "fish"]
then it creates an array of:
[1, 1, 1, 1]
If the array is:
["bird", "fish"]
then it creates an array of:
[1, 1]
How can I do this?
You can use the Array.prototype.map method:
var input = ["foo", "bar", "baz"];
var mapped = input.map(function () { return 1; });
Just create a new array of equal length and use the fill function.
var myArray = ["dog","cat","monkey"];
var secondArray = new Array(myArray.length).fill(1);
// es6
var array = ["t1", "something", "bird", "dog", "cow", "fish"]
array.map(() => 1); // => [1, 1, 1, 1, 1, 1]
// if you don't care if they are strings
'1'.repeat(array.length).split(''); //=> ["1", "1", "1", "1", "1", "1"]

Categories