Application of array instance method

Array has many instance methods. Some methods will not change the existing array, but return a new array, and some methods will change the original array. The methods listed in this article are all extracted from real cases of specific projects.

1. forEach

Execute the given function once for each element of the array without changing the original array.

let obj = {a: 1, b: 2, c: 3};
Object.keys(obj).forEach((k) => (obj[k] = '1')); // Change all value s of an object to '1'
// {a: '1', b: '1', c: '1'}

2. push

Adds one or more elements to the end of an array and returns the new length of the array. Change the original array.

const dates = ["2022-01-27 12:00:00", "2022-01-27 14:00:00"];
const xAxisData = [];
dates.forEach((item) => {
  const date = item.split(' ').join('\n');
  xAxisData.push(date);
});

// xAxisData:  ['2022-01-27\n12:00:00', '2022-01-27\n14:00:00']

3. includes

Judge whether an array contains a specified value. If so, return true; otherwise, return false. The original array will not be changed.

const category = ["oxygenerator", "sphygmomanometer"];
category.includes("oxygenerator");

// true

4. map

Create a new array, and the result is that each element in the array is the return value after calling the provided function once. The original array will not be changed.

const options = [{word: "aged", score: 23}, {word: "middle-aged person", score: 63}];
const data = options.map((item, index) => {return {...item, index: index + 1}});
// data: [{word: "elderly", score: 23, index: 1}, {word: "middle-aged", score: 63, index: 2}];

Generally, when the data returned by the interface needs to adjust (add) a certain attribute, map is very suitable.

When you do not intend to use the returned new array but use map is against the original design intention, please use forEach or for of instead.

5. every

Tests whether all elements in an array can pass the test of a specified function. It returns a Boolean value. The original array will not be changed.

const data = [{name: 'Uploading', status: 1}, {name: 'Parsing', status: 2}, {name: 'Conversion in progress', status: 3}, {name: 'Conversion succeeded', status: 4}];
const completeStatus = data.every(item => item.status === 4);
if (completeStatus) {
  console.log("Status completed");
}

In the above example, test whether the status attribute of each element of the array is equal to 4. If all are 4, return true, indicating the completion status. For example, it can be used to judge whether a list needs to continue rotation training. The rotation training can be stopped when the status has been completed.

6. filter

Create a new array that contains all the elements of the test implemented by the provided function. The original array will not be changed.

// Attribute of a commodity
const tags = ["Fuselage texture", "Product style", "Fuselage size", "Fuselage weight", "Mobile convenience design"];
const top3Tags = tags.filter((item, index) => index < 3);
// top3Tags: [body texture "," product style "," body size "]

In the above example, only the first three items of the array are taken.

// Attribute of a commodity, including evaluation score
const goods = [{name: "Fuselage texture", score: 9}, {name:"Product style", score: 11}, {name:"Fuselage size", score: 19}, {name:"Fuselage weight", score: 5}, {name:"Mobile convenience design", score: 44}];
const positiveGoods = goods.filter(item => item.score > 15);
// positiveGoods: [{name: "body size", score: 19}, {name: "mobile convenience design", score: 44}]

In the above example, take the items whose score value of the array element is greater than 15.

7. join

Concatenates all elements of an array (or an array like object) into a string and returns the string. If the array has only one item, the item is returned without a delimiter. The original array will not be changed.

// Some listed Internet Medical Enterprises
const brand = ["JD health", "Ali jiangkang", "Safe, good doctor"];
const brandStr = barnd.join();
// brandStr: "JD health, alibaba will be healthy, safe and good doctor"

8. sort

Use the in-situ algorithm to sort the elements of the array and return the array. The default sort order is built when converting elements to strings and then comparing their sequences of UTF-16 code unit values. The original array will not be changed.

const goods = [{name: "Fuselage texture", score: 9}, {name:"Product style", score: 11}, {name:"Fuselage size", score: 19}, {name:"Fuselage weight", score: 5}, {name:"Mobile convenience design", score: 44}];
const positiveGoods = goods.sort((a, b) => a.score - b.score); // Sort by score from small to large (sort in ascending order)

// positiveGoods: [{name: "body weight", score: 5}, {name: "body texture", score: 9}, {name: "product style", score: 11}, {name: "body size", score: 19}, {name: "mobile convenience design", score: 44}]

9. find

Returns the value of the first element in the array that satisfies the provided test function. Otherwise, it returns undefined. The original array will not be changed.

const options = 
[
    {
        "label": "brand",
        "name": "brand",
        "value": [
            "Fish jump",
            "OMRON",
            "Haier",
            "Philips"
        ]
    },
    {
        "label": "message_source",
        "name": "information sources ",
        "value": [
            "Tmall comments",
            "Suning comments",
            "Jingdong comments"
        ]
    }
];
const key = "message_source";
const obj = options.find((item) => item.label === key);
// obj: {
//    "label": "message_source",
//    "name": "information source",
//    "value": [
//        "Tmall comments",
//        "Suning comments",
//        "Jingdong comments"
//    ]
//}

In the above example, find the label attribute equal to message_source element.

10. concat

Used to merge two or more arrays. This method does not change the existing array, but returns a new array. The original array will not be changed.

let options = [];
// Seeking brand intersection
const a = new Set(["Fish jump", "OMRON", "Kefu", "Haier", "Lepu", "Jiuan", "Meiling"]);
const b = new Set(["Lepu", "Renhe", "Kefu", "OMRON", "Oggs", "Oxygen Elf", "Haier"]);
const intersect = [...new Set([...a].filter((x) => b.has(x)))];  // ["Omron", "Kefu", "Haier", "Lepu"]
intersect.forEach((elem) => {
  options= options.concat([elem]);
});

// options: ['Omron', 'Kefu', 'Haier', 'Lepu']

11. [reduce](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce0

Execute a reducer function (executed in ascending order) provided by you for each element in the array, and summarize its results into a single return value. The original array will not be changed.

// Convert a two-dimensional array into a one-dimensional array
const arr = [["Philips", "Haier"], ["Suning comments", "Jingdong comments"]];
const arr2 = arr.reduce((a, b) => a.concat(b));

// arr2: ["Philips", "Haier", "Suning review", "JD review"];

In the above example, a two-dimensional array is transformed into a one-dimensional array.

const x = [1, 2, 3, 4, 5, 6, 7];
const x2 = x.reduce((a, b) => a + b);
// x2: 28

In the above example, sum. Similarly, a very classic problem: the sum added from 1 to 100 can also be obtained in this way!

12. some

Test whether at least one element in the array has passed the provided function test. It returns a value of type Boolean. The original array will not be changed.

const data = [{name: 'Conversion in progress', status: 3}, {name: 'Conversion succeeded', status: 4}];
const uncompleteStatus = data.some(item => item.status === 3);
if (uncompleteStatus) {
  console.log("Status incomplete");
}

In the above example, test whether the status attribute of at least one element of the array is equal to 3. If so, return true, indicating the unfinished state. For example, it can be used to judge whether a list needs to continue rotation training. Rotation training is required before the status is completed.

Keywords: Javascript filter map sort find

Added by wscreate on Thu, 27 Jan 2022 22:17:58 +0200